@Mock annotation creates a mock implementation for the class it is annotated with.
@InjectMocks also creates the mock implementation, additionally injects the dependent mocks that are marked with the annotations @Mock into it.
In UserServiceTest we are mocking UserRespository which means we don’t care about how the repository layer works. As the dependencies are mocked, we have to define how the method calls to the mocked object should behave, we can do that by using the method call chain Mockito.when().thenReturn()
xxxxxxxxxx
@ExtendWith(SpringExtension.class)
public class UserServiceTest {
@InjectMocks
private UserServiceImpl userService;
@Mock
private UserRepository userRepository;
private String TEST_EMAIL = "test@gmail.com";
@Test
public void shouldGetUser() {
User user = User.builder()
.id("id")
.firstName("firstName")
.lastName("lastName")
.phone("phone")
.email(TEST_EMAIL)
.role(UserRoles.ADMIN)
.password("password")
.active(false)
.build();
when(userRepository.findUserByEmail(TEST_EMAIL)).thenReturn(Mono.just(user));
Mono<UserDto> userMono = userService.getUser(TEST_EMAIL);
StepVerifier
.create(userMono)
.consumeNextWith(newUser -> {
assertEquals(newUser.getEmail(), TEST_EMAIL);
})
.verifyComplete();
}
@Test
public void shouldGetUserNotFound() {
when(userRepository.findUserByEmail(TEST_EMAIL)).thenReturn(Mono.empty());
Mono<UserDto> userMono = userService.getUser(TEST_EMAIL);
StepVerifier
.create(userMono)
.expectErrorMatches(throwable -> throwable instanceof UserNotFoundException)
.verify();
}
}