Mockito FAQ


by Gualtiero Testa and contributors. Last update on 2015-10-06

Examples project can be found at

Many thanks to Szczepan Faber and the Mockito team for their job.

Table of Contents

  1. Resources
  2. General
  3. Installation
  4. Creating mocks
  5. Stubbing methods
  6. Matching
  7. Verifying and capturing

1. Resources

1.1 Examples Where to find all Examples
1.2 Mockito Home The Mockito pr/wiki/Rulesoject home page
1.3 Mockito on Maven Central
1.4 Download latest Mockito jar where to download latest release.
1.5 Tutorial on testing abstract classes
1.6 PowerMock Home Page

2. General

2.1 Why mocking ?

Unit tests requires the code under test (the unit) to be isolated from the rest of the application.
Tested code dependencies should be “broken” in order to achieve the required isolation.
Using dummy or mocked classes instead of the real classes is a common solution to achieve this isolation.
Creating mocks by hand is a time-consuming activity.
Mocking libraries exist to easy the job to create mocked version of the application classes.

2.2 Why Mockito ?

Mockito is the most popular mocking library. So why not?

2.3 What is a Mockito mock ?

A mock is a proxy of the real class. Being a proxy, Mockito can control the behaviour of the class methods.

The standard behaviour of a mock method is do nothing when invoked. The code which invokes the mock method is so isolated because mock method calls have no effects.

If the real class method is not void (it returns something), the mocked version also returns something: the default value for the return type.

Methods which returns a primitive (int, long,…) when mocked will return zero (0).
Methods which returns an object (String,…) when mocked will return null.
Methods which returns a collection (List,Set,…) when mocked will return an empty collection (not null).

2.4 What is a Mockito spy ?

A spy is a mock where the standard behaviour of the mocked methods is to call the real class method.

The difference between a real class and its spy version is that Mockito can stub the spy methods so we can change the class behaviour.

2.5 How to enable Mockito annotations ?

Mockito annotations like @Mock are enabled in two different ways, with and without a test runner.

First way is using the Mockito test runner, annotating the test class with th
@RunWith(MockitoJUnitRunner.class) annotation (valid for jUnit only).
See Example 02 for a complete example

As alternative, anntations can be enabled as following:

    public void before() {

See Example 03 for a complete example.

Using the runner is the suggested way if no other runners (like, for ex. the Spring framework runner) should be used.
In this case using MockitoAnnotations.initMocks() method is a valid solution.

3. Installation

3.1 Which version should I install ?

Mockito 2 is currently in beta status. Mockito 1.x is stable. The suggested dependency is mockito-core. See this wiki page for details.
You can find current release and status on Mockito Home where there are also links to Maven Central and JAR download areas. See Section 1: Resources for all links.

3.2 What is the difference between mockito-core and mockito-all ?

Mockito-core is the main Mockito library.
Mockito-all includes optional dependencies and it is only available on Mockito 1.x.

3.3 How to install Mockito in a Maven project ?

Add following dependency in project pom.xml:


4. Creating mocks

4.1 How to create a mock (without annotations) ?

A mock can be created using the Mockito.mock() method as following:

    AClass inst = new AClass();
    AClass mock = Mockito.mock(AClass.class);

Here AClass is the class to be mocked. Object inst is an real instance of AClass while
mock is its mocked instance.

Note: in this example, the first line is just for comparison purposes.

See example01 for a complete example.

4.2 How to create a mock (with annotations) ?

A mock can be created using the @Mock annotation as following:

    @Mock AClass mock;

Mockito will create the mock before each test execution.

Here AClass is the class to be mocked. Object inst is an real instance of AClass while
mock is its mocked instance.

Note: in this example, the first line is just for comparison purposes.

See example 02 and example 03 for a complete example.

See question 2.3 to see how to enable the annotations.

4.3 Can I mock an interface ?

Yes. Mockito can create a mock from an interface even if there is no implementation class.

    interface ADependency {...}

    class My {
        private ADependency dependency;

    class MyTest {
        @Mock private ADependency dependency;

This is handy when you should test a class which uses an API which is not yet implemented or when the implementing class is injected in the class My using a dependency injection container (Spring, J2EE,…).

See example 04 for a complete example.

4.5 Can I mock an abstract class ?

Yes. Mockito can create a mock of an abstract class even if there is no concrete implementation class.

This is useful to test the logic of the non-abstract method in the abstract class.

Abstract classes cannot be instantiated (we cannot do new AbstractClass() in Java) so Mockito syntax is a bit more complex in this case.

    public abstract TheClass { .. }

    class MyTest {
        private TheClass sut = Mockito.spy(TheClass.class);

Important: here we are creating a spy of the class under test. This is a special case because the class is abstract. We usually do not mock the class under test but its dependencies.

See example 05 for a complete example.

See resource 1.5 for a complete tutorial.Mockito.when ( #method# )

4.6 Can I mock a final class ?

No. Mockito cannot create a mock of a final class.

You can consider to use PowerMock (see reference 1.6)

5. Stubbing methods

5.1 What is a stubbed method ?

Mockito can control the behaviour of the mock methods like changing their return value or throwing an exception if invoked.

For example

   class ADependency {
      public String getName() { return "Fred"; }

The real class method will return Fred when invoked.

Creating a mock of this class

    ADependency dep = Mockito.mock(ADependency.class);
    // dep.getName() returns null

the mock method (dep.getName()) will return null when invoked. Null is the default return value for mocked String methods.

We can change the return value by using the Mockito.when(....).thenReturn(...) method:

    Mockito.when( dep.getName() ).thenReturn("Paul");
    // dep.getName() now returns "Paul"

Now the mock method will return Paul. We have stubbed the getName() method.

The syntax is simple: Mockito.when ( #mock.method()# ).thenReturn ( #return value# );

See example 01 for a complete example.

6. Matching and capturing

6.1 What is a matcher ?

A method parameter matcher is a comparison function which allows Mockito

  • to limit a method stubbing only when the passed parameter matches
  • to verify if a method has been invoked with a matching parameter

Mockito matchers are in the org.mockito.Matchers class.

An example:

   class ADependency {
      public int countRecordsBySinger(String singerName) { ..}

In the test class:

   ADependency dep = Mockito.mock(ADependency.class);

   // Stub the method regardless the singer
   Mockito.when(dep.countRecordsBySinger( Matchers.anyString() )).thenReturn(5);

   // dep.countRecordsBySinger("Sting") will return 5
   // dep.countRecordsBySinger("One Direction") will return 5   

   // Stub the method only when the singer is Sting
   Mockito.when(dep.countRecordsBySinger( Matchers.eq("Sting") )).thenReturn(5);

   // dep.countRecordsBySinger("Sting") will return 5
   // dep.countRecordsBySinger("One Direction") will return null 

See example 06 for a complete example.

7. Verifying and capturing

7.1 What does verifying means ?

After the method under test execution, we can ask Mockito about how all the mocks have been used: if a specific mock has been used, if a specific method has been invoked, how many times, with which parameters and in which order.

Mockito.verify(#mockA).#method1() will fail if the method1 of mockA has not been invoked exactly one time (never or two or more times).

Verification is a way to observe the side effects of the method under test. Together with the method return value, it allow us to check (assert) if the method logic is correct.

7.2 What is a capture ?

We can record (capture) the parameters passed to an invoked mock method during test execution.

Capture is useful when the passed parameter is local to method under test and it is not observable by other ways.

An example:

    class ADependency {
        public void saveUser(User user); { ..}

    class TheClass {

        private ADependency dependency;

        void createNewUser(String pFirstName, String pFamilyName, int pAge) {
            String name = pFamilyName + ' ' + pFirstName;
            User user = new User(name, pAge);

In the test class we can have :

    ADependency dep = Mockito.mock(ADependency.class);

    ArgumentCaptor<User> capUser = ArgumentCaptor.forClass(User.class);

    sut.createNewUser(firstName, familyName, age);

    User capturedUser = capUser.getValue();
    // capturedUser is the User instance built inside createNewUser()
    // add here proper assertions on capturedUser contents using its getters

Line 3: we create a arguments captor
Line 7: the captor capture() will capture the parameter passed to saveUser during the test.
Line 8: we extract the parameter from the captor