Tasty Test Tip: Matching generic typed classes in Mockito

Say you have a arbitrary class under test, which is dependent on a class DataProcessor which has a method with the following signature:

you might want to stub it with Mockito 1.9.5 in the following way to match the generic typed class:

However running this, gives the following error:

This is caused by the generic typed MulitvaluedMap.

Solution:

Run the test and it will pass (these lines at least :-)!

Original Post

Using ArgumentMatchers with Mockito

Mockito is a mock framework which you can use to write simple and clean tests. One of it’s nice features is the ArgumentMatcher. With the ArgumentMatcher you can determine the outcome of your mocked service or repository based on any condition you want.

Imagine we have a CandyService which can get a list of candies which are liked by a specific customer. This service uses the external ChocalateService which specifically checks if the customer likes chocolate. Continue reading

Tasty Test Tip: Test final and static methods with PowerMock and Mockito

Two of the most famous mocking frameworks EasyMock and Mockito, don’t offer out of the box support for mocking final and static methods.

It is often said on forums that “you don’t want that” or “your code is badly designed” etc. Well this might be true some of the time, but not all of the time. Continue reading

Tasty Test Tip: Using ArgumentCaptor for generic collections with Mockito

Mockito has a very nice feature that allows you to verify what parameters were used when a method was executed.

For example:

However, when using generic typed objects, some problems rise up.
For example, the following won’t work:

This is obviously not a Mockito problem, but a generics problem.

To solve this, follow these two steps:

1. use the @Captor annotation.

2. initialize the Mockito annotations in your initialization method (add one if you don’t have one).

And presto! You can now capture the parameters that were used when a to be verified method was executed.