I been having discussion with colleagues recently about good use of matchers. Consider the following sample:
@RunWith(MockitoJUnitRunner.class)
public class LoginRestServiceImplTest {
@Mock
private LoginService loginService;
@InjectMocks
private LoginRestService loginRestService = new LoginRestServiceImpl();
private LoginRequest loginRequest;
private LoginResponse loginResponse;
@Before
public void setUp() throws Exception {
loginRequest = new LoginRequest("Username","Password");
}
@Test
public void thatUserCanLoginWhenUserAndPassCorrect() {
// Given
loginResponse = new LoginResponse();
loginResponse.setSuccess(true);
when(loginService.login(anyString(), anyString())).thenReturn(loginResponse);
// When
LoginResponse result = loginRestService.login(loginRequest);
// Then
assertTrue("User Can login", result.isSuccess());
}
@Test
public void thatUserCantLoginWhenPasswordIncorrect() {
// Given
loginResponse = new LoginResponse();
loginResponse.setSuccess(false);
loginResponse.setError(INCORRECT_PASSWORD);
when(loginService.login(anyString(), anyString())).thenReturn(loginResponse);
// When
LoginResponse result = loginRestService.login(loginRequest);
// Then
assertFalse("User Can't login", result.isSuccess());
assertEqual("Error Code is Incorrect Password", INCORRECT_PASSWORD, loginResponse.getError());
}
}
Note this is just a sample. Normally we would use a spring MVC for unit testing a REST service.
But is the use of anyString() valid. Does it mean we are being too broad with the mocking criteria?
Is there anything else that is wrong with this style?