Java, Mockito, Software Development

Mock Method To Return Different Values in Mockito

This post shows how to mock a method that returns unique values for different arguments in Mockito. For example, the return values vary according to the method argument.

Sample Codes To Mock

Suppose we have the following Java classes.

The first class represents a DAO that returns a pet’s directly from the database when searching by pet Id. Also, this is the Java class whose method we will mock later on to make it return different values.

Next, we have the service class, which is the target of our testing effort. It uses the DAO class to retrieve pet names from some persistent storage. Also, the service class has some business logic on the String value that the DAO method returns.

For example, when the DAO method returns null, the service method throws a RuntimeException with a specific message – “Something wrong happened while retrieving a pet by Id.”

Moreover, when the DAO method returns a String value that contains “<” (less-than character), the service method then throws another RuntimeException with a different message – “Pet name contains codes for possible XSS attack.”

For our purpose, the target of our test effort is the MyPetService service class. So far, so good? Ready to move on to the next section? Very well!

Mock Method To Return Different Values

We will mock the DAO method three times with different arguments to give us various string values in our test method. For Pet 1, we mock the DAO method to return null, a blank (“”) String value for Pet 2, and JavaScript codes for Pet 3.

We created three stubbings (in Mockito vocabulary), and we need to test with all three argument values – 1, 2, and 3. If we skip any of the values, Mockito throws an UnnecessaryStubbingException.

How To Fix “Please remove unnecessary stubbings or use ‘lenient’ strictness”

In the previous section, we created three stubs using the three arguments values – 1, 2, and 3. We need to test with these values. Otherwise, we get the following Mockito error.

Although we can fix this by annotating the test class or its only method as follows.

However, our test will not be as extensive as it should be when we do that.

Verify Mock Method Returns Different Values

Finally, we assert that the combination of stubs and arguments should throw RuntimeException with specific messages.

The complete unit test codes are as follows.

There you go! Try it out in your unit tests!

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like