Skip to content
zrlw edited this page Aug 31, 2021 · 18 revisions

What is Mockito?

Mockito is a mocking framework for Java. Mockito allows convenient creation of substitutes of real objects for testing purposes. Enjoy clean tests with mock objects, improved TDD experience and beautiful mocking API. See the main page or examples for more.

Is it really a mocking framework?

There is a bit of confusion around the vocabulary. Technically speaking, Mockito is a Test Spy framework. Usually developers use Mockito instead of a mocking framework. Test Spy framework allows to verify behaviour (like mocks) and stub methods (like good old hand-crafted stubs).

Why is Mockito so simple?

To promote simple test code that hopefully pushes the developer to write simple and clean application code. I wrote this paragraph long before version 1.5. Mockito is still quite lean but the number of features increased because many users found valid cases for them. It's OSS after all, isn't it?

What are the limitations of Mockito

Mockito 3.x specific limitations
Mockito 2.x specific limitations
  • Requires Java 6+
  • Cannot mock constructors
  • Cannot mock static methods
  • Cannot mock equals(), hashCode(). Firstly, you should not mock those methods. Secondly, Mockito defines and depends upon a specific implementation of these methods. Redefining them might break Mockito.
  • Mocking is only possible on VMs that are supported by Objenesis. Don't worry, most VMs should work just fine.
  • Spying on real methods where real implementation references outer Class via OuterClass.this is impossible. Don't worry, this is extremely rare case.
Mockito 1.x Specific limitations
  • Needs Java 5+
  • Cannot mock final classes
  • Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.
  • Cannot mock static methods
  • Cannot mock constructors
  • Cannot mock equals(), hashCode(). Firstly, you should not mock those methods. Secondly, Mockito defines and depends upon a specific implementation of these methods. Redefining them might break Mockito.
  • Mocking is only possible on VMs that are supported by Objenesis (Note Objenesis is in version 2.1). Don't worry, most VMs should work just fine.
  • Spying on real methods where real implementation references outer Class via OuterClass.this is impossible. Don't worry, this is extremely rare case.

Do you mock classes & interfaces?

Yes, the api is the same for mocking classes or interfaces.

What values do mocks return by default?

In order to be transparent and unobtrusive all Mockito mocks by default return 'nice' values. For example: zeros, falseys, empty collections or nulls. Refer to javadocs about stubbing to see exactly what values are returned by default.

Can I have xxxx feature?

Please send us or a pull request an example where you need something more than Mockito can offer.

Can I mock private methods?

No. From the standpoint of testing... private methods don't exist. More about private methods here.

Is Mockito thread-safe?

For healthy scenarios Mockito plays nicely with threads. For instance, you can run tests in parallel to speed up the build. Also, you can let multiple threads call methods on a shared mock to test in concurrent conditions. Check out a timeout() feature for testing concurrency.

However Mockito is only thread-safe in healthy tests, that is tests without multiple threads stubbing/verifying a shared mock. Stubbing or verification of a shared mock from different threads is NOT the proper way of testing because it will always lead to intermittent behavior. In general, mutable state + assertions in multi-threaded environment lead to random results. If you do stub/verify a shared mock across threads you will face occasional exceptions like: WrongTypeOfReturnValue, etc.

Can I verify toString()?

No. You can stub it, though. Verification of toString() is not implemented mainly because:

  • When debugging, IDE calls toString() on objects to print local variables and their content, etc. After debugging, the verification of toString() will most likely fail.
  • toString() is used for logging or during string concatenation. Those invocations are usually irrelevant but they will change the outcome of verification.

Can I "reset" a mock?

Recently we decided to go on with this feature for tricky scenarios where mocks are created by the container (see issue 55). Before that, the lack of a reset method was deliberate to promote good testing habits and to make the API simpler.

Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified tests. The discussion about this feature was here.

What are unfinished verification/stubbing errors?

Mockito validates if you use it correctly all the time. Examples of incorrect use:

  //Oups, someone forgot thenReturn() part:
  when(mock.get());

  //Oups, someone put the verified method call inside verify() where it should be outside:
  verify(mock.execute());

  //Oups, someone has used EasyMock for too long and forgot to specify the method to verify:
  verify(mock);

Mockito throws exceptions if you misuse it so that you will know if your tests are written correctly. The only problem is that Mockito does the validation next time you use the framework. Therefore sometimes the exception is thrown in the next test and you have to manually find the previous test that was not written correctly.

Why does Mockito keep ThreadLocal state?

Mockito uses ThreadLocal state to implement a gorgeous mocking syntax in a language full of constraints (yes, it's java). Fortunately, every time you interact with Mockito framework it validates the ThreadLocal state in case you misused the api.

Can I thenReturn() an inlined mock() ?

Unfortunately you cannot do this:

  when(m.foo()).thenReturn(mock(Foo.class));
  //                         ^

The reason is that detecting unfinished stubbing wouldn't work if we allow above construct. We consider this as a 'trade off' of framework validation (see also previous FAQ entry). However you can slightly change the code to make it working:

  //extract local variable and start smiling:
  Foo foo = mock(Foo.class);
  when(m.foo()).thenReturn(foo);

Can I stub chained getters?

  when(mock.getA().getB()).thenReturn(...);

This sort of stubbing, e.g. mock to return mock, to return mock, etc. should be used very sporadically, ideally never. It clearly points out violation of the Law of Demeter. You don't want to mess with Demeter. Since you have been warned check out Mockito deep stubs.

Why this FAQ doesn't have answers to my questions?

Do you have any suggestions? Write to our mailing list.

Clone this wiki locally