Auto inject dependencies in JUnit using Mockito

While writing unit tests, you often have to mock dependencies like services or controllers. Often  a constructor is used to autowire the dependencies as shown in the example below. In the Test class I instantiated the ContactService using a contactRepository Mock object

The test class:

In the previous example you always have to Autowire the constructor and bind the dependencies to the class variables. In the next example the code is cleaner by autowiring the mocking objects, so you don’t have to create a custom constructor or setters to set the dependencies, which makes your code more concise and easier to read.

The test class:

Take a note of the “RunWith(MockitoJUnitRunner.class)” annotation. This annotation will initialize the annotated mock objects. An alternative is to use “MockitoAnnotations.initMocks(this)” in a setup method to initalize the annotated mock objects.

More tips can be found on the Mockito RefCard: or take a look at the mockito site:

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.