Mocking Void Methods with Mockito
When dealing with observer patterns, mocking methods with void return types can present challenges. One such case is encountering difficulties in mocking a class with a method like addListener, which returns void.
To mock a method with no return value, Mockito provides a set of methods: doThrow(), doAnswer(), doNothing(), and doReturn(). These methods allow you to specify the behavior of the mocked method.
For instance, to specify that the addListener method throws an exception when called, you can use:
Mockito.doThrow(new Exception()).when(instance).addListener(any(Listener.class));
Alternatively, you can chain multiple behaviors together. For example, the following code throws an exception on the first call to addListener and then does nothing on subsequent calls:
Mockito.doThrow(new Exception()).doNothing().when(instance).addListener(any(Listener.class));
In the provided World class, you can mock the setState method using the doAnswer method, as shown below:
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());
The above is the detailed content of How to Mock Void Methods in Mockito: A Guide to doThrow, doAnswer, doNothing, and doReturn?. For more information, please follow other related articles on the PHP Chinese website!