- Mocking calls to a method that returns void using Mockito
- 2. Stubbing void methods
- 4. Conclusion
- Mockito mock void method
- Throwing an exception with a mocked void method
- Verifying that a void method is called
- Capturing void method arguments
- Stub a void method to run other code
- Calling the real method
- Conclusion
- Mockito Mock Void Method
- Mockito Mock Void Method
- Mockito mock void method example
- Mockito mock void method with exception
- JUnit Mockito mock void method example
- TestNG Mockito void method example
- Mock Void method with Mockito
- Why we need to mock void method?
- How to mock void method in mockito?
- 1) Using doNothing()
- Example using doNothing() for void method
- Without using doNothing() for void method
- Example of argument capture using doNothing()
- 2) Using doAnswer() for void method
- 3) Throw exception using doThrow()
- 4) Real method call using doCallRealMethod()
- Fast track reading
- Reference:
- Related Topics:
Mocking calls to a method that returns void using Mockito
Mockito is one of the best testing frameworks used to mock objects and verify methods behavior. In this article, we are going to present a way to stub a method that returns void instead of an Object. Stubbing void methods require a different approach.
2. Stubbing void methods
First, let’s check what happens when we try to use the when(. ).then(. ) notation to configure a method that returns void.
package com.frontbackend.libraries.mockito; import static org.mockito.Mockito.when; import org.junit.Test; import org.mockito.Mock; @RunWith(MockitoJUnitRunner.class) public class MockitoVoidMethodStubbingTest < @Mock private SimpleInterface simpleInterface; interface SimpleInterface < void doSomething(); >@Test(expected = RuntimeException.class) public void testStubbingVoidMethod() < when(simpleInterface.doSomething()).thenThrow(new RuntimeException("Something is not right")); simpleInterface.doSomething(); >>
In the following example test, we have a simple interface with the doSomething() void method that we want to mock. We want to throw an exception every time we call that method.
Using when(simpleInterface.doSomething()).thenThrow(new RuntimeException(«Something is not right»)); will give us a compilation error:
Error:(19, 41) java: 'void' type not allowed here
The compiler doesn’t like void methods inside brackets thats why we need to use a different solution here — we should use doReturn()|doThrow()| doAnswer()|doNothing()|doCallRealMethod() family of methods.
Let’s use doThrow().when() notation instead of when().thenThrow() :
package com.frontbackend.libraries.mockito; import static org.mockito.Mockito.doThrow; import org.junit.Test; import org.mockito.Mock; @RunWith(MockitoJUnitRunner.class) public class MockitoVoidMethodStubbingTest < @Mock private SimpleInterface simpleInterface; interface SimpleInterface < void doSomething(); >@Test(expected = RuntimeException.class) public void testStubbingVoidMethod() < doThrow(new RuntimeException("Something is not right")).when(simpleInterface) .doSomething(); simpleInterface.doSomething(); >>
This code was compiled successfully, without any errors. Test also passed without any issues.
According to the Mockito docs the do. ().when(. ) family of methods we used to:
- stub void methods,
- stub methods on spy objects,
- stub the same method more than once, to change the behavior of a mock in the middle of a test.
We can use these methods also as an alternative with when() for all stubbing calls.
4. Conclusion
In this article, we presented how to stub a method that returns void in Mockito tests. This kind of methods should be treated differently. Instead of when().then() notation we must use do[. ]().when(. ) syntax.
As usual, the code used in this article is available under our GitHub repository.
Mockito mock void method
In this post, we will look at how to mock void methods with Mockito. Methods that return void can’t be used with when. This means we have work with the following methods to mock a void method:
- doThrow(Throwable. )
- doThrow(Class)
- doAnswer(Answer)
- doNothing()
- doCallRealMethod()
This is the class we will be using for the examples. It’s a small class with only one void method that prints “Hello, » followed by the input to the console.
Throwing an exception with a mocked void method
To make a void method throw an exception, we use doThrow() . The exception we pass to the doThrow() is thrown when the mocked method is called.
You can only use unchecked exceptions or exceptions that are declared in the method signature. The doThrow() call below wouldn’t work because IOException is a checked exception and not declared as part of the doAction() method signature.
Verifying that a void method is called
With Mockito, we use verify() to check if a method has been called. The example below shows two ways of implementing this. times(1) is the default value, so you can omit it to have more readable code.
Capturing void method arguments
We can also capture the arguments that we pass to a method. To do that we can create an ArgumentCaptor or use lambda matchers. Line 4 till 6 shows how to create and use the ArgumentCaptor . Lines 9 uses a lambda matcher. At line 11, we also use a lambda matcher, but with a method reference to keep it more readable.
Stub a void method to run other code
We can also stub a method to let it perform other behavior. We use Mockito’s doAnswer() to change the behavior. The example below changed the message that gets printed to the console. The method will now print good morning instead of hello.
Calling the real method
By default, stubbed will do nothing when you call them. To call the actual method, you can use doCallRealMethod() . Doing this will let you call the actual method of the class you mock.
Conclusion
In this post, we looked at the different ways of mocking void methods when you write tests using Mockito.
Mockito Mock Void Method
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.
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
- doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void.
- 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.
Mock Void method with Mockito
Hey guys! After our previous blog on difference between thenReturn and thenAnswer mockito methods, we are back with yet another interesting blog on Mockito. Here, we shall discuss «How to Mock Void method with Mockito». Let’s get started!
When writing code, there is always at least one method that returns ‘void’, and at some point in time we need to mock ‘void’ method. So how do we go about it? Let us together figure this out in the following blog using mockito.
Mockito is one of the most famous mocking framework used for writing unit tests. If you are new to mocking you can know more at mockito website.
In this blog we will cover,
Why we need to mock void method?
Let’s assume we have a method. In this method we call another void method. Now, when you want to write test case for this method, how can we test that the void method was called? Also, if the correct parameters were passed to void method?
In this case mockito comes to our rescue.
Let’s take an example, we have a UserService class. In this class we have a updateName() method.
Now, we want to write unit test for UserService class and mock userRepository.
But the only thing we need to verify in this test case is that updateName() method from userRepository is called with correct set of parameters.
For this purpose we need to mock updateName() method, capture the arguments and verify the arguments.
One of the most important point to note here is that, we can not just mock void method using when-then mechanism of mockito. Because, when() method of mockito works with return value and does not work when method is void.
How to mock void method in mockito?
In Mockito we can use different methods to call real method or mock void method. We can use one of the options as per requirements
- doNothing() : Completely ignore the calling of void method, this is default behavior
- doAnswer() : Perform some run time or complex operations when void method is called
- doThrow() : Throw exception when mocked void method is called
- doCallRealMethod() : Do not mock and call real method
1) Using doNothing()
If we just want to completely ignore the void method call, we can use doNothing().
In mocking, for every method of mocked object doNothing is the default behavior. Hence, if you don’t want to verify parameters, use of doNothing is completely optional. Following all codes perform similar behavior,
Example using doNothing() for void method
@Test public void testUpdateNameWithDoNothingVerifyRepositoryCall()
Without using doNothing() for void method
@Test public void testUpdateNameWithOutDoNothingVerifyRepositoryCall()
Example of argument capture using doNothing()
We can do different things with argument capture. Here, we will just verify the captured value
@Test public void testUpdateNameUsingArgumentCaptor() < ArgumentCaptoridCapture = ArgumentCaptor.forClass(Long.class); ArgumentCaptor nameCapture = ArgumentCaptor.forClass(String.class); doNothing().when(mockedUserRepository).updateName(idCapture.capture(),nameCapture.capture()); userService.updateName(1L,"void mock test"); assertEquals(1L, idCapture.getValue()); assertEquals("void mock test", nameCapture.getValue()); >
2) Using doAnswer() for void method
If we do not want to call real method, however need to perform some runtime operation doAnswer is used.
Let’s take an example of doAnswer where we will print and verify the argument using doAnswer
@Test public void testUpdateNameUsingDoAnswer() < doAnswer(invocation ->< long String name = invocation.getArgument(1); System.out.println("called for id: "+id+" and name: "+name); assertEquals(1L, id); assertEquals("void mock test", name); return null; >).when(mockedUserRepository).updateName(anyLong(),anyString()); userService.updateName(1L,"void mock test"); verify(mockedUserRepository, times(1)).updateName(1L,"void mock test"); >
3) Throw exception using doThrow()
If we want to throw an exception when method is called, we can use doThrow() method of mockito.
Let’s take an example where we will throw InvalidParamException when updateName() method is called with null id.
@Test(expected = InvalidParamException.class) public void testUpdateNameThrowExceptionWhenIdNull()
4) Real method call using doCallRealMethod()
Sometimes it is necessary to call the real method from mocked object, in such case we need to use doCallRealMethod(), because doNothig() is the default behavior.
In the following example real method from userRepository will be called even though it is a mocked object.
@Test public void testUpdateNameCallRealRepositoryMethod()
Fast track reading
- Void method is mostly mocked to check if it is called with correct parameters
- For mocking void method when-then mechanism of mockito does not work because it needs return value
- Void methods can be handled using doNothing(), doAnswer(), doThrow() or doCallRealMethod()
- doNothing() : Completely ignore the void method
- doAnswer() : Perform some run time or complex operations
- doThrow() : Throw exception when mocked void method is called
- doCallRealMethod() : Do not mock and call real method
- For mocked object doNothing is the default behavior for every method