-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
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.
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).
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?
- Requires Java 8+
- Cannot mock constructors ( support mocking object construction since 3.5.0, see https://javadoc.io/static/org.mockito/mockito-core/3.12.4/org/mockito/Mockito.html#49 )
- 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
viaOuterClass.this
is impossible. Don't worry, this is extremely rare case.
- 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
viaOuterClass.this
is impossible. Don't worry, this is extremely rare case.
Yes, the api is the same for mocking classes or interfaces.
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.
Please send us or a pull request an example where you need something more than Mockito can offer.
No. From the standpoint of testing... private methods don't exist. More about private methods here.
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.
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 oftoString()
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.
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.
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.
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.
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);
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.
Do you have any suggestions? Write to our mailing list.