Home » Core Java » Mockito » Mockito: How to mock a void method call

About Mohammad Meraj Zia

Mohammad Meraj Zia
I did my Engineering in Information Technology from IET, Lucknow, India. Currently doing MSc in Information Technology from Derby University. I have worked in Java/J2EE domain for the last 10 years. Have good understanding of Payment and Finance domains.

Mockito: How to mock a void method call

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 mock a void method call 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 ‘MockitoMockVoidMethod’.
Figure 1. Create Java Project

Figure 1. Create Java Project

  • 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’.
Figure 2. Java Package

Figure 2. Java Package

  • 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 Dependencies

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 (non-beta) 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.

4. Stub

The role of the test stub is to return controlled values to the object being tested. These are described as indirect inputs to the test. We replace a real object with a test-specific object that feeds the desired indirect inputs into the system under test.

4.1. doThrow()

In this section we will see how we can mock void methods which throw exceptions. To do this we make use of doThrow() method of Mockito class. Stubbing void methods requires a different approach from when(Object) because the compiler does not like void methods inside brackets.

doThrow(new Exception()).when(mockObject).methodWhichThrowException();
mockedObject.methodWhichThrowException();

4.2 doAnswer()

Use doAnswer() when you want to stub a void method with generic org.mockito.stubbing.AnswerAnswer specifies an action that is executed and a return value that is returned when you interact with the mock.

doAnswer(new Answer() {
   public Object answer(InvocationOnMock invocation){
        Object[] args = invocation.getArguments();
        Mock mock = invocation.getMock();
        return null;
    }
}).when(mock).someMethod();

4.3 doNothing()

Use doNothing() for setting void methods to do nothing. Beware that void methods on mocks do nothing by default! However, there are rare situations when doNothing() comes handy:

4.3.1 Stubbing consecutive calls on a void method:

doNothing().doThrow(new IllegalArgumentException()).when(mockObject).someVoidMethod();

//does nothing the first time:
mockObject.someVoidMethod();

//throws IllegalArgumentException the next time:
mockObject.someVoidMethod();

4.3.2 When you spy real objects and you want the void method to do nothing:

Map map = new HashMap();
Map spy = spy(map);

//let's make clear() do nothing
doNothing().when(spy).clear();

spy.put("one", "1");

//clear() does nothing, so the map still contains "one", "1"
spy.clear();

5. Example

In this section we will see the working example of mocking a void method. First we will create a simple class with one void method.

VoidMethodClass.java

package com.javacodegeeks;

public class VoidMethodClass {

  public void voidMethodThrowingExcetion(boolean check) {
    if (check) {
      throw new IllegalArgumentException();
    }
  }
}

Now we will create a test class for this where we will mock this method using Mockito.

VoidMethodClassTest.java

package com.javacodegeeks;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

public class VoidMethodClassTest {

  private VoidMethodClass mock;

  @Test
  public void testVoidMethodThrowingExcetion() {
    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) {
      // Expected
    }
  }
}

6. Download the source file

In this example we saw how we can mock void classes using Mockito

Download
You can download the full source code of this example here: MockitoMockVoidMethod
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of