Junit 整合-ApiHug准备-测试篇-013-#应用

时间:2024-04-22 08:41:57

基本的几个服务类:

└─mockito
    │  User.java
    │
    ├─repository
    │      MailClient.java
    │      SettingRepository.java
    │      UserRepository.java
    │
    └─service
            DefaultUserService.java
            Errors.java
            UserService.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) {
    // Given
    user = new User("Jerry", 12);
    when(userRepository.insert(any(User.class)))
        .then(
            new Answer<User>() {
              int sequence = 1;

              @Override
              public User answer(InvocationOnMock invocation) throws Throwable {
                User user = (User) invocation.getArgument(0);
                user.setId(sequence++);
                return user;
              }
            });

    userService = new DefaultUserService(userRepository, settingRepository, mailClient);

    // When
    User insertedUser = userService.register(user);

    // Then
    verify(userRepository).insert(user);
    Assertions.assertNotNull(user.getId());
    verify(mailClient).sendUserRegistrationMail(insertedUser);
}