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?
Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.
A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With