Home > Mobile >  How to test custom exception with Mockito
How to test custom exception with Mockito

Time:01-06

I am trying to learn unit testing with Mockito. This is a method I wrote to authenticate the users that tries to log in:

public class AuthenService {
    
    private UserRepo userRepo;  

    public User authenticate(String username, String password) throws UserNotFoundException {
        User user = null;
        if (userRepo.validate(username, password)) {
            user = userRepo.findUsername(username);
            return user;
        } else {
            throw new UserNotFoundException("User not found!");
        }
    }
}

userRepo is an interface with these two abstract methods:

public interface UserRepo{
    
    boolean validate(String username, String password);
    
    User findUsername(String username);
    
}

This is my testing code:

public class Test {

    AuthenService as;
    UserRepo ur;
    
    @BeforeEach
    public void init() {
        ur = mock(UserRepo.class);
        as = new AuthenService(ur);
    }
    
    @Test
    public void authenticate() throws UserNotFoundException {
        when(as.authenticate("abc", "123")).thenThrow(new UserNotFoundException("User not found!"));
    }
}

I suppose as.authenticate("abc", "123") should throw an exception because the DB is empty right now. But I think I am wrong, and I have no idea how to fix it. Can anyone please explain to me? Thank you.

CodePudding user response:

One unit test would be to expect an exception if the validation fails. To that, consider (working example here:

   @Test(expected = UserNotFoundException.class)
    public void authenticate() throws UserNotFoundException {
        when(ur.validate("abc", "123")).thenReturn(false);

        // test
        as.authenticate("abc", "123");
    }

Note the parameter to the @Test annotation that declares the test should throw the exception.

CodePudding user response:

You are stubbing instead of asserting in your test, so basically you are not testing anything. A test should include at least one assertion, so it should look something similar to this:

assertThrows(UserNotFoundException.class, () -> as.authenticate("abc", "123"));
  • Related