Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Mockito, how to stub a method with return type void which throws an exception when a certain argument is passed?

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?

like image 383
rmoestl Avatar asked Mar 28 '13 13:03

rmoestl


People also ask

How do you mock method which returns void?

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.

What is stub method in Mockito?

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.


1 Answers

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.

like image 84
rmoestl Avatar answered Oct 27 '22 08:10

rmoestl