Skip to content

Instantly share code, notes, and snippets.

@danilobatistaqueiroz
Last active February 11, 2018 05:07
Show Gist options
  • Save danilobatistaqueiroz/ff645b8651c220dd21c5a01186a063f0 to your computer and use it in GitHub Desktop.
Save danilobatistaqueiroz/ff645b8651c220dd21c5a01186a063f0 to your computer and use it in GitHub Desktop.
Working With Mockito

Working With Mockito

Using Mockito for mocking objects

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.

Test Doubles

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.

Purposes

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.

Limitations

Mockito has certain limitations. For example:
cannot mock static methods, private methods, constructors.
cannot mock equals(), hashCode() methods.

Powermock for mocking static 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.

Mocking final classes

Since Mockito v2 it is possible to mock final classes.
This feature is incubating and is deactivated by default.


Links:

https://github.com/mockito/mockito/wiki/FAQ#what-are-the-limitations-of-mockito

http://www.vogella.com/tutorials/Mockito/article.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment