🤗 ApiHug × {Postman|Swagger|Api...} = 快↑ 准√ 省↓
- GitHub - apihug/apihug.com: All abou the Apihug
- apihug.com: 有爱,有温度,有质量,有信任
- ApiHug - API design Copilot - IntelliJ IDEs Plugin | Marketplace
这里简单演示一个对 mockito
的通过扩展的整合,例子在 junit5>mockitoopen in new window
例子中我们将演示, 如果通过 mockito
实现对于 @Mock
对象自动用 mockito
扩展例子。
#依赖
testImplementation 'org.mockito:mockito-core:4.6.1'
testImplementation 'org.mockito:mockito-junit-jupiter:4.6.1'
#应用
基本的几个服务类:
└─mockito│ User.java│├─repository│ MailClient.java│ SettingRepository.java│ UserRepository.java│└─serviceDefaultUserService.javaErrors.javaUserService.java
测试类
@ExtendWith(MockitoExtension.class)
public class UserServiceUnitTest {UserService userService;SettingRepository settingRepository;@Mock UserRepository userRepository;@Mock MailClient mailClient;}`@Mock` 为我们测试注入 mock 对象, 在每个测试进行前,初始化 fixture:```java@BeforeEach
void init(@Mock SettingRepository settingRepository) {userService = new DefaultUserService(userRepository, settingRepository, mailClient);lenient().when(settingRepository.getUserMinAge()).thenReturn(10);when(settingRepository.getUserNameMinLength()).thenReturn(4);lenient().when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(false);this.settingRepository = settingRepository;
}
注意 Mockito.lenient
Mockito 对处理未使用的 mock 对象会抛出 UnsupportedStubbingException
所以这里用 lenient 避免抛出这样的异常。
然后看具体测实测用例:
@Test
void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) {// Givenuser = new User("Jerry", 12);when(userRepository.insert(any(User.class))).then(new Answer<User>() {int sequence = 1;@Overridepublic User answer(InvocationOnMock invocation) throws Throwable {User user = (User) invocation.getArgument(0);user.setId(sequence++);return user;}});userService = new DefaultUserService(userRepository, settingRepository, mailClient);// WhenUser insertedUser = userService.register(user);// Thenverify(userRepository).insert(user);Assertions.assertNotNull(user.getId());verify(mailClient).sendUserRegistrationMail(insertedUser);
}