Mockito is a framework to help you create stubs and mocks quickly if you do Unit Testing.
Tutorial for version 1.0
This tutorial is unit testing framework agnostic. For examples on how to use it with specific unit testing frameworks please check the integrations section.
Before you will be able to create your mock objects you need to tell Mockito to prepare for it. You do it by calling:
and providing all the classes to mock in given test case. Since the bytecode generation is an asynchronous process it is recommended to use one of the integration test cases as they address this issue. You may find more answers inAsmock documentation.
After preparing classes you can create mock objects by invoking:
Then setup the System Under Test (SUT)
And execute tested code.
Given the testedFunction looks like this:
Notice that there is no 'unexpected call' exception.
Instead you are free to choose what you want to verify:
The full test would look like this:
As you can see, verification happens where assertions go. Not before the tested code. Important note is that verify() is equivalent to verify(times(1)).
If you need to stub dependency, you define it upfront.
When used in test it would look like this:
It may be useful to verify or define stubbing with various arguments at a time or have ability of matching the specific cases. For that purpose Mockito provides Matchers. Below example verifies any arguments passed to the function:
Similar you can do with stubbing:
As you can see you can either use explicit values or matchers when defining stubs or verifying. But you cannot mix it within single stub definition or verification. So for instance:
is invalid. Mockito will not be able to figure out which argument type to match against the any() matcher. You may want to verify multiple executions of a method at time. It's easy. Just tell how to verify:
Sometimes you may want to make sure method has not been called. Do it by verifying: