How to mock void methods with Mockito
Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow()
,doAnswer()
,doNothing()
,doReturn()
family of methods from Mockito framework to mock void methods.
For example,
Mockito.doThrow(new Exception()).when(instance).methodName();
or if you want to combine it with follow-up behavior,
Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
Presuming that you are looking at mocking the setter setState(String s)
in the class World below is the code uses doAnswer
method to mock the setState
.
World mockWorld = mock(World.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
System.out.println("called with arguments: " + Arrays.toString(args));
return null;
}
}).when(mockWorld).setState(anyString());
Mocking a void method in the same class that is under test with mockito and junit5?
Do nothing works for me. Just pay attention to the calling order
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
doNothing().when(yourMock).yourMethod(yourArgs);
This thread treats a similar problem, using a spy to mock specific methods with static factories should work. I've seen people doing to reverse operation (Use a Mock and then call the real method in some specific cases), but never tried it personally..
Mockito with void method in JUnit
You can either use doNothing or doThrow on your mock to mock the behaviour of your mock.
Mockito.doNothing().when(employeeDAO).delete(any());
or
Mockito.doThrow(new RuntimeException()).when(employeeDAO).delete(any());
However, doNothing is not actually needed as this would be the default behaviour for a mock function with a void return type.
You may want however to verify
that this method was called. For example:
verify(employeeDAO).delete(any());
Mockito test a void method throws an exception
The parentheses are poorly placed.
You need to use:
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
^
and NOT use:
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
^
This is explained in the documentation
Mockito mocking the void methods
For void methods, you need to stub the action first.
Mockito.doAnswer(invocation -> {
// grab args and remove from cart
})
.when(cartService) // mocked cartService
.removeItem(cart, rowKey, messages); // You can use argumentMatchers here
Mockito Mock a static void method with Mockito.mockStatic()
In general mocking static calls is the last resort, that is not supposed to be used as default approach.
For example, for testing the code, that works with file system, there are better means. E.g. depending on the junit
version either use TemporaryFolder
rule or @TempDir
annotation.
Also, please note, that Mockito.mockStatic
might significantly slow down your tests (e.g. look at the notes below).
Having said the caution above, find the snippet below, that shows how to test, that file got removed.
class FileRemover {
public static void deleteFile(Path filePath) throws IOException {
Files.delete(filePath);
}
}
class FileRemoverTest {
@TempDir
Path directory;
@Test
void fileIsRemovedWithTemporaryDirectory() throws IOException {
Path fileToDelete = directory.resolve("fileToDelete");
Files.createFile(fileToDelete);
FileRemover.deleteFile(fileToDelete);
assertFalse(Files.exists(fileToDelete));
}
@Test
void fileIsRemovedWithMockStatic() throws IOException {
Path fileToDelete = Paths.get("fileToDelete");
try (MockedStatic<Files> removerMock = Mockito.mockStatic(Files.class)) {
removerMock.when(() -> Files.delete(fileToDelete)).thenAnswer((Answer<Void>) invocation -> null);
// alternatively
// removerMock.when(() -> Files.delete(fileToDelete)).thenAnswer(Answers.RETURNS_DEFAULTS);
FileRemover.deleteFile(fileToDelete);
removerMock.verify(() -> Files.delete(fileToDelete));
}
}
}
Notes:
Mockito.mockStatic
is available in Mockito 3.4 and above, so check you're using correct version.The snippet deliberatly shows two approaches:
@TempDir
andMockito.mockStatic
. When run both tests you'll notice thatMockito.mockStatic
is much slower. E.g. on my system test withMockito.mockStatic
runs around 900 msec vs 10 msec for@TempDir
.
Related Topics
Find Where Java Class Is Loaded From
Changing Edittext Bottom Line Color with Appcompat V7
Using Static Variables in Android
Firebase No Properties to Serialize Found on Class
How to Get the Ip of the Computer on Linux Through Java
How to Get Chromedriver Process Pid Using Java
Swt Expandlistener Executes Before Collapse Occurs on Linux
Error While Loading Shared Libraries: Libjli.So in Java
Why Is 08 Not a Valid Integer Literal in Java
Converting Java Bitmap to Byte Array
Java.Lang.Numberformatexception: Invalid Double: " "
How to Make My Arrayadapter Follow the Viewholder Pattern
Obtaining the Thread Id for Java Threads in Linux
Java.Lang.Runtime Exception "Cannot Run Program"
What Determines the Current Working Directory of Tomcat Java Process
Java File Locking Mechanism for File Based Process Communication