Mockito is a popular mock framework which can be used in conjunction with JUnit.
Mockito allows you to create and configure mock objects.
Using Mockito simplifies the development of tests for classes with external dependencies significantly.
A unit test should test functionality in isolation.
Side effects from other classes or the system should be eliminated for a unit test, if possible.
This can be done via using test replacements (test doubles) for the real dependencies.
Test doubles can be classified like the following:
- dummy object: is passed around but never used, i.e., its methods are never called.
- fake objects: have working implementations, but are usually simplified, i.e., they use an in memory database.
- stub class: is a partial implementation for an object, usually don’t respond to anything outside what’s programmed in for the test.
- mock object: is a dummy implementation for an interface or a class in which you define the output of certain method calls.
Mocking or mock frameworks allows testing the expected interaction with the mock object.
Using mock, the class to be tested wont have any hard dependency on external data.
Mockito has certain limitations. For example:
cannot mock static methods, private methods, constructors.
cannot mock equals(), hashCode() methods.
Mockito cannot mock static methods.
For this you can use Powermock.
PowerMock provides a class called "PowerMockito" for creating mock/object/class and initiating verification, and expectations.
Since Mockito v2 it is possible to mock final classes.
This feature is incubating and is deactivated by default.
https://github.com/mockito/mockito/wiki/FAQ#what-are-the-limitations-of-mockito