Report this

What is the reason for this report?

Mockito Mock Void Method

Published on August 3, 2022
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 author

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Category:
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?

Was this helpful?

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

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

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.