I'm learning mock and I wonder if I could use a code similar as this:
Mockito.when(service.authenticateUser(test)).thenReturn(any());
to validate the success of authentication.
service.AuthenticateUser(User user):
@Override
public Player authenticateUser(User login) throws AuthenticationException {
Player find = new Player();
for (Player player : initializedPlayers) {
if (login.getEmail().equals(player.getEmail()) && login.getPassword().equals(player.getPassword())) {
loggedPlayer = player;
return player;
}
}
throw new AuthenticationException("Incorrect email and/or password");
}
As you can see, the login
method returns a Player
, but is there a possible way to tell Mockito that I only want to get something back, if its valid? So I would be able to test wheter the authentication was succesful or not, e.g.:
Mockito.when(service.authenticateUser(test)).thenReturn(any(Player.class));
assertNotNull(service.authenticateUser(test));
^this method currently not working, it gives failed test on stub.
EDIT: I tried approaching this in two different way:
@Test
public void testFailAuthWithMockedService(){
DefaultSportsBettingService service = mock(DefaultSportsBettingService.class);
User test = new User("test","test");
Mockito.when(service.authenticateUser(test)).thenReturn(any(Player.class));
assertNotNull(service.authenticateUser(test));
}
@Test
public void testSuccessfulAuthWithMockedService(){
DefaultSportsBettingService service = mock(DefaultSportsBettingService.class);
User test = new User("validName","validPassword");
Mockito.when(service.authenticateUser(test)).thenReturn(any());
assertNotNull(service.authenticateUser(test));
}
These codes comply, but I'm not sure if they are truely good.
Additional information: This method is called in my main at the very beginning:
@Override
public Player authenticateUser(User login) throws AuthenticationException {
Player find = new Player();
for (Player player : initializedPlayers) {
if (login.getEmail().equals(player.getEmail()) && login.getPassword().equals(player.getPassword())) {
loggedPlayer = player;
return player;
}
}
throw new AuthenticationException("Incorrect email and/or password");
}
The main():
(that part of the main which uses the authentication)
while(true) {
try {
dsbs.authenticateUser(view.readCredentials());
if(dsbs.getLoggedPlayer() != null){
break;
}
} catch (AuthenticationException ae) {
ae.printStackTrace();
}
}