Reputation: 3155
Here is the principal Mockito documentation for stubbing void methods with exceptions. However, the example in the Mockito doc stubs a parameterless method. What if the method has parameters and the method throws an Exception if the a parameter does not fulfills the contract?
So for the following class...
public class UserAccountManager {
/**
* @throws Exception if user with provided username already exists
*/
public void createAccount(User user) throws Exception {
// db access code ...
}
}
... how can UserAccountManager.createAccount be mocked with Mockito so that it throws an Exception if a certain User object is passed as an argument to the method?
Upvotes: 6
Views: 17758
Reputation: 3155
The Mockito doc already shows an example of how to stub a parameterless void method with exceptions.
However, for stubbing a void method with parameters and exceptions, do this:
Since the return type of createAccount is void, you have to use doThrow:
User existingUser = ... // Construct a user which is supposed to exist
UserAccountManager accountMng = mock(UserAccountManager.class);
doThrow(new Exception()).when(accountMng).createAccount(eq(existingUser));
Note the usage of the eq Matcher. If the argument's type (in this case User) does not implement equals on its own you can also try to use the refEq Matcher.
Upvotes: 14