Java, Web and Mobile


Mocking framework comparison: Mockito

Java|Java EE|Testing

Unit testing is essential to produce good software. In consequence, I would claim that any Java developer knows (and uses) JUnit. As a unit test is intended to cover only a very small piece of code – in most cases a certain Java class – we want it to be independent of other classes. To achieve that we need to mock out these classes. In the Java world there are a couple of mocking frameworks around. This is the first post of a short series that introduces and compares the mostly used candidates. We will start with Mockito.

What is a mock?

If you are new to this topic, you will meet unfamiliar terms like mock, spy or stub. Let us have a short look at the differences. A mock is something like a place holder for a real object. It does provide the identical interface like the mocked object. However, calling a mock’s method will not have any effects. You can do asserts on desired invocations of a mock or define behaviour when a certain method is called (for example throw an exception). A spy is used to introduce a kind of observer for a real object. So, you can do asserts on invocations, too. In contrast to a mock a spied object still acts like it would do in production. A stub (or test stub) replaces implementation of a certain method or class. You use a stub over a mock when a method calls needs to execute more or less sophisticated code (for example when replacing database access using a map). Sometimes stubs are termed fakes.


Development of Mockito was started around 2008. Today it can be seen as old bull in world of mocking frameworks. And indeed, I meet Mockito in nearly 100% of my projects. Latest stable version is 1.10.19 from December 2014. Version 2.0 is in beta status since the beginning of 2015. However, the API did not change a lot. I hope to see a stable release within the next few months. So, we will use the latest 2.0 SNAPSHOT for this article.

Using Mockito

Using maven we only need to add a new dependency to or pom.xml as you can see in listing 1.

Listing 2 shows a first very simple unit test using Mockito. Please note: I created a small demo project providing classes DemoService, DemoDAO, DemoEntity and so on. This project can be found at GitHub.

Running the test will give us a green result. So, let’s have a look at the test code in detail. Class DemoService uses CDI to inject DemoDAO. Using Mockito we can imitate this style of programming: The tested class needs annotation @InjectMocks. This will tell Mockito to create a new instance of DemoService and inject needed dependencies. Mockito can inject every mocked or spied object defined as field within the same class. Thanks annotation @Mock the field dao is initialized as mock and will be injected into the service object. @Spy will create a spied object. Mockito’s “dependency injection” works based on types. Having the same type for multiple fields will lead to unpredictable behaviour. If a dependency is not found, the field will just be null. Following this approach Mockito is not settled to a certain dependency injection framework (you could of course use Spring, too). At least we need to tell JUnit to use Mockito’s JUnit runner using class annotation @RunWith(MockitoJUnitRunner.class).

Looking at the test save() you won’t see any asserts. This is correct, since Mockito uses keyword verify for assertions. Nevertheless Mockito uses a nice fluent API for verifications. So, Mockito.verify(dao).update(entity) verifies that method update() of mocked object dao was called for a certain the mocked object dao. You can also check the number of invocations using Mockito.times() (per default Mockito expects exactly one invocation). Mockito.times(0) could also be expressed using Mockito.never().


We have already seen the @Mock annotation. Mockito does not provide a stub annotation. If you need a stub, just create a mock and stub certain methods. In listing 3 I added a second test that changes the behaviour of our DemoEntity object.

Mockito.mock() is just another way to create a mock. Now, our entity is a mock we can stub method isNew(). For trivial return values you can just use Mockito’s thenReturn() method.

When it is getting more complex you can just write an Answer as I did in listing 4.

If your answer relates on method parameters, you can use InvocationOnMock.getArgument() to retrieve those.


Spying is very similar to handling of mocks. In listing 5 I wrote another test that creates a spy on DemoEntity and asserts that method isNew() is called.

In contrast to creating a mock Mockito.spy() needs a concrete instance of the class to be spied. Mockito allows stubbing of spied objects. However, developers are discouraged to use this feature since the mix of real and stubbed methods might lead to undetected errors.

Argument matching

So far all verifications just used exact matching of input parameters. In general, you should use exact matching where you can. Nevertheless, there are use cases where you want to match a method parameter against a wider range of values. The test in listing 6 ensures that the DAO’s method load() is never called for any instance of DemoEntity.

Instead of our concrete instance entity we pass a kind of wildcard to method load. Such wildcards can be created using factory ArgumentMatchers. There are several methods for primitive types, collections or string operations or you use ArgumentMatchers.any(Class) for any other type. If you need a more sophisticated matching, you can write an own matcher using ArgumentMatchers.argThat().

If you are familiar with Mockito prior to version 2: Class org.mockito.Matchers has been renamed to org.mockito.ArgumentMatchers due to the name clash with Hamcrest. Class org.mockito.Mockito extends ArgumentMatchers. So, you could also call Mockito.any() alternatively.

Argument capturing

If you want to peform further assertions on parameters passed to a mock, there is an alternative to ArgumentMatcher called ArgumentCaptor. Using ArgumentCaptors you are able to use JUnit’s asserts instead of Mockito’s verify which might feel more familiar. Listing 7 demonstrates how to use the ArgumentCaptor.

At first we create an ArgumentCaptor of generic type DemoEntity using the ArgumentCaptor’s factory method. In addition, we tell Mockito that every time when dao.update() is called the passed parameter should be captured. After calling the service we can now perform asserts on any captured value. If there was only one invocation, simply use ArgumentCaptor.getValue(). If you expect more calls, use ArgumentCaptor.getAllValues() to get a list of all captured parameters.

Verifying execution order

Sometime you need to ensure that certain operations are performed before others will. For example, in context of our demo service we want to ensure that the entity’s validation method is called before passing the entity to the dao. Listing 8 shows how to implement that using Mockito.

Mockito provides a method called inOrder() accepting 1..n mocks and returning an object of type InOrder. Using the InOrder object we can perform verifiy() calls the same way shown in the first examples above. However, Mockito now ensures that the order of verify calls matches the order of real method invocations in our test. Finally, you can use verifyNoMoreInteractions() to ensure that no other untracked methods have been called.

Mocking of static, final or new

A known limitation of Mockito is the inability to mock or spy final or static classes and methods as well as to control objects created using keyword new within a tested method. If you are facing this problem, there are some commons workarounds:

  • avoid final/static


  • refactor your code to wrap calls to final/static methods in a kind of decorator


  • use a Factory


  • use PowerMock: PowerMock extends Mockito and adds ability of mocking static, final and some other stuff

Personally, I am not a fan of PowerMock (since it seems to require a lot of memory when running unit tests). I prefer a combination of the first three workarounds mentioned.


Mockito is a powerful framework with only a few limitations. API and concepts are clear and consequently used. All needed operations are grouped in class org.mockito.Mockito. So, new developers will get used to Mockito very fast. The named limitations have only lead to slightly trouble in my projects.

In the next part of this series I will have a look at the alternative framework JMockit.