Mockito Test Case Example
A unit test should test a class in isolation. Side effects from other classes or the system should be eliminated if possible. Mockito lets you write beautiful tests with a clean & simple API. In this example we will learn how to write a simple test case using Mockito. Tools and technologies used in this example are Java 1.8, Eclipse Luna 4.4.2
1. Introduction
Mockito is a popular mocking framework which can be used in conjunction with JUnit. Mockito allows us to create and configure mock objects. Using Mockito simplifies the development of tests for classes with external dependencies significantly. We can create the mock objects manually or we can use the mocking framewors like Mockito, EasyMock. jMock etc. Mock frameworks allow us to create mock objects at runtime and define their behavior. The classical example for a mock object is a data provider. In production, a real database is used, but for testing a mock object simulates the database and ensures that the test conditions are always the same.
2. Creating a project
Below are the steps required to create the project.
- Open Eclipse. Go to File=>New=>Java Project. In the ‘Project name’ enter ‘MockitoExample’.
- Eclipse will create a ‘src’ folder. Right click on the ‘src’ folder and choose New=>Package. In the ‘Name’ text-box enter ‘com.javacodegeeks’. Click ‘Finish’.
- Right click on the package and choose New=>Class. Give the class name and click ‘Finish’. Eclipse will create a default class with the given name.
3.1 Declaring mockito dependency
For this example we need the junit and mockito jars. These jars can be downloaded from Maven repository. We are using ‘junit-4.12.jar’ and ‘mockito-all-1.10.19.jar’. There are the latests versions available as per now. To add these jars in the classpath right click on the project and choose Build Path=>Configure Build Path. The click on the ‘Add External JARs’ button on the right hand side. Then go to the location where you have downloaded these jars. Then click ok.
If you are using Gradle you can do:
repositories { jcenter() }
dependencies { testCompile “org.mockito:mockito-core:1.+” }
4. Code
In this section we will see some simple code examples.
4.1 Mock
To mock the class we make use of the mock()
method of the Mockito
class. It creates a mock object of a given class or interface:
public static <T> T mock(Class<T> classToMock)
Below is the code snippet we use to mock:
// Create Mock Stack<String> mockStack = Mockito.mock(Stack.class);
Mockito also supports the creation of mock objects based on the @Mock
annotation. You annotate the class with @Mock
as below:
@Mock private IReportGenerator reportGenerator;
Then you annotate the class (which you want to test) which has the reference to this mocked class with @InjectMocks
:
@InjectMocks private ReportGeneratorService reportGeneratorService;
After this you need to initialize the mocks. We can do this by calling the initMocks()
method of MockitoAnnotations
class.
@Before public void setUp() { MockitoAnnotations.initMocks(this); }
4.2 Verify
Let us see the usage of verify()
method of Mockito class. This verifies that certain behavior happened once. You can also use another overloaded method which takes an extra integer argument (times(int)
). The arguments passed are compared using equals()
method. Let’s see an example now.
// Create Mock Stack<String> mockStack = Mockito.mock(Stack.class); // Use mock object mockStack.add("Test verify"); Mockito.verify(mockStack).add("Test verify");
4.3 Stub
In this section we will see how we can stub a method call. To stub a method we will make use of the when()
method. Stubbing can be overridden: For example common stubbing can go to fixture setup but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing. Once stubbed, the method will always return stubbed value regardless of how many times it is called. Last stubbing is more important – when you stubbed the same method with the same arguments many times. Although it is possible to verify a stubbed invocation, usually it’s just redundant.
By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.
The other method we use for stubbing is thenReturn()
. It sets a return value to be returned when the method is called. See the code snippet below:
// Create Mock Stack<String> mockStack = Mockito.mock(Stack.class); Assert.assertEquals(mockStack.capacity(), 0); // Stub Mockito.when(mockStack.capacity()).thenReturn(10); Assert.assertEquals(mockStack.capacity(), 10); Mockito.verify(mockStack);
4.4 Argument matchers
Mockito verifies argument values in natural java style: by using an equals()
method. Sometimes, when extra flexibility is required then you might use argument matchers:
Stack<String> mockStack = Mockito.mock(Stack.class); Mockito.when(mockStack.get(Mockito.anyInt())).thenReturn("PASS"); Assert.assertEquals(mockStack.get(0), "PASS"); Assert.assertEquals(mockStack.get(10), "PASS"); Mockito.verify(mockStack, Mockito.times(2)).get(Mockito.anyInt());
Argument matchers allow flexible verification or stubbing. Be reasonable with using complicated argument matching. The natural matching style using equals()
with occasional anyX()
matchers tend to give clean & simple tests. Sometimes it’s just better to refactor the code to allow equals()
matching or even implement equals()
method to help out with testing. If you are using argument matchers, all arguments have to be provided by matchers.
4.5 Stub void method
In this section we will see how we can stub void methods with exception. We will make use of the doThrow()
method of the Mockito class
mock = Mockito.mock(VoidMethodClass.class); Mockito.doThrow(new IllegalArgumentException()).when(mock).voidMethodThrowingExcetion(false); mock.voidMethodThrowingExcetion(true); Mockito.doThrow(new IllegalArgumentException()).when(mock).voidMethodThrowingExcetion(true); try { mock.voidMethodThrowingExcetion(true); Assert.fail(); } catch (IllegalArgumentException e) { }
5. Download the source file
This was a very simple example of using Mockito to write unit tests. There are lots of other features which Mockito provides. You can look at the Mockito website for more details.
You can download the full source code of this example here: MockitoExample