Exceptions and Timeouts
Contents
1. Throwing Exceptions
Is possible to make a mock method throw an exception that is not defined in the method signature.
java
@Test (expected = EmptyCredentialsException.class)
public void testAuthenticateEmptyCredentialsException() throws EmptyCredentialsException {
AuthenticatorInterface authenticatorMock;
AuthenticatorApplication authenticator;
authenticatorMock = Mockito.mock(AuthenticatorInterface.class);
authenticator = new AuthenticatorApplication(authenticatorMock);
when(authenticatorMock.authenticateUser("", ""))
.thenThrow(new EmptyCredentialsException());
authenticator.authenticate("", "");
}As you can see, is almost identical to adding return values to the mock. The only difference is that we have to call thenThr ow(), passing the exception instance we want to be thrown. And, of course, we have to handle the exception; in this case, we have used the expected rule to "assert" the exception.
2. Verification with timeout
If we want to ensure that our authe nticateUser() method runs in, for example, 100 milliseconds or less, we would do the following:
java
// ...
verify(authenticatorMock, timeout(100)).authenticateUser(username, password);
// ...The timeout verification can be combined with the method call, so, we could verify the timeout for n method calls:
AuthenticatorApplicationTest.java
java
// ...
verify(authenticatorMock, timeout(100).times(1)).authenticateUser(username, password);
// ...