Tutorial

Mockito Mock Void Method

Published on August 3, 2022
author

Pankaj

Mockito Mock Void Method

Most of the times Mockito when() method is good enough to mock an object’s behavior. But when we have to mock a void method, we can’t use when().

Mockito Mock Void Method

Mockito provides following methods that can be used to mock void methods.

  1. doAnswer(): We can use this to perform some operations when a mocked object method is called that is returning void.
  2. doThrow(): We can use doThrow() when we want to stub a void method that throws exception.

Let’s create a simple class with a void method that we will mock in our test classes.

package com.journaldev;

public class Employee {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		if (name == null)
			throw new IllegalArgumentException("Employee Name can't be null");
		this.name = name;
	}

}

Mockito mock void method example

Mockito doAnswer() method takes Answer as argument. It’s a functional interface so we can use lambda expression for its implementation.

doAnswer((i) -> {
	System.out.println("Employee setName Argument = " + i.getArgument(0));
	assertTrue("Pankaj".equals(i.getArgument(0)));
	return null;
}).when(emp).setName(anyString());

Notice that return null statement is required since we are mocking void method.

Mockito mock void method with exception

Below code snippet shows how to use doThrow() method to mock void methods with the exception.

doThrow(IllegalArgumentException.class).when(emp).setName(null);

JUnit Mockito mock void method example

Here is a complete example in JUnit where I am using Mockito to mock void method.

package com.journaldev.mockito.voidmethod;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;

import com.journaldev.Employee;

class JUnitMockitoVoidMethod {

	@Test
	void test_mockito_void() {
		Employee emp = mock(Employee.class);

		doThrow(IllegalArgumentException.class).when(emp).setName(null);

		doAnswer((i) -> {
			System.out.println("Employee setName Argument = " + i.getArgument(0));
			assertTrue("Pankaj".equals(i.getArgument(0)));
			return null;
		}).when(emp).setName(anyString());

		when(emp.getName()).thenReturn("Pankaj");

		assertThrows(IllegalArgumentException.class, () -> emp.setName(null));

		emp.setName("Pankaj");
		assertEquals("Pankaj", emp.getName());
	}

}

TestNG Mockito void method example

Since JUnit 5 and TestNG annotations are so similar, we don’t have to any code specific changes in above class to switch from JUnit 5 to TestNG. Just remove the JUnit 5 import statements and add below imports to change testing framework from JUnit to TestNG.

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;

import org.testng.annotations.Test;

You can download the complete project code from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 22, 2020

I want to mock a void method whose one input state got changed in method body like public void doSomething(SomeBusinessClass1 input1,SomeBusinessClass2 input2,SomeBusinessClass3 input3) { if (openartion on input1){ input3.setOneFiled(calcValue(input2)); } } How can do this ?

- shyam

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.