What is the best way to mock void methods using Mockito?

In Mockito, to mock void methods, you can use doNothing(), doThrow(), or doAnswer().

For your specific case, since you’re trying to observe the state change in the World class, you can use doNothing() to mock the setState() method if it has no actual side effect or if you want to avoid triggering it in the test.

Here’s how you can mock the void method setState() and test your code:

import static org.mockito.Mockito.*;

public class WorldTest {

    @Test
    public void testWorld() {
        // Mock the World class
        World w = mock(World.class);
        
        // Mock the setState method to do nothing
        doNothing().when(w).setState(anyString());

        // Add the listener and trigger the doAction method
        w.addListener(this);
        w.doAction(mock(Action.class), new Object());

        // You can now verify that setState was called with the expected values
        verify(w).setState("i received");
        verify(w).setState("i finished");
    }

    // Implement the Listener interface
    @Override
    public void doAction() {
        // Do something
    }
}

In this case, doNothing().when(w).setState(anyString()) ensures that when setState() is called inside the doAction method, it doesn’t actually modify the state, but we can still verify its behavior.