Mockito


Mockito is an open source testing framework for Java released under the MIT License. The framework allows the creation of test double objects in automated unit tests for the purpose of test-driven development or behavior-driven development.
The framework's name and logo are a play on mojitos, a type of drink.

Features

Mockito allows developers to verify the behavior of the system under test without establishing expectations beforehand. One of the criticisms of mock objects is that there is a tight coupling of the test code to the system under test. Mockito attempts to eliminate the expect-run-verify pattern by removing the specification of expectations. Mockito also provides some annotations for reducing boilerplate code.

Origins

Mockito began by expanding on the syntax and functionality of EasyMock.

Example

Consider this decoupled Hello world program; we may unit test some of its parts, using mock objects for other parts.

package org.wikipedia.examples;
import java.io.IOException;
public class HelloApplication

The result of HelloApplication launching will be the following:

application: hello world

Unit test for HelloActable component may look like this:

package org.wikipedia.examples;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.wikipedia.examples.HelloApplication.HelloActable;
import org.wikipedia.examples.HelloApplication.HelloAction;
import org.wikipedia.examples.HelloApplication.Greeter;
public class HelloActionUnitTest

It uses mock objects for the Greeter and Appendable interfaces, and implicitly assumes the next use case:

unitTest : hi world

Integration test code for testing HelloActable wired together with Greeter may look like the following:

package org.wikipedia.examples;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.wikipedia.examples.HelloApplication.HelloActable;
import org.wikipedia.examples.HelloApplication.HelloAction;
import org.wikipedia.examples.HelloApplication.Greeter;
import org.wikipedia.examples.HelloApplication.HelloGreeter;
public class HelloActionIntegrationTest

It uses mock objects only in place of Appendable interfaces, uses the real implementations for other interfaces, and implicitly assumes the next use case:

integrationTest says welcome universe

As can be seen from the import statements of HelloActionUnitTest and HelloActionIntegrationTest classes, it is necessary to put some Mockito jars and JUnit jars in your class path to be able to compile and run the test classes.