Mocking Void Methods with Mockito
How can one mock methods with a void return type using the Mockito framework? This particular question arises frequently in scenarios where an object method does not return a value but instead performs an action.
Overcoming the Challenge
The Mockito API offers a range of options to handle this situation, including methods like doThrow(), doAnswer(), doNothing(), and doReturn().
Example Implementation
Consider the following example scenario:
public class World { private String state; // Setter for state public void setState(String s) { this.state = s; } } public class WorldTest { @Test public void testingWorld() { World mockWorld = mock(World.class); // Mock the setState method using doAnswer doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); System.out.println("Called with arguments: " + Arrays.toString(args)); return null; } }).when(mockWorld).setState(anyString()); // Call the mock method and observe the output mockWorld.setState("Mocked"); } }
By employing the doAnswer method, we can specify custom behavior for the mock setState method. In the example above, we print the arguments passed to the method, providing visibility into its invocation.
The above is the detailed content of How to Mock Void Methods in Mockito?. For more information, please follow other related articles on the PHP Chinese website!