如何使用 Mockito 模拟 void 方法

public class World {

    List<Listener> listeners;

    void addListener(Listener item) {
        listeners.add(item);
    }

    void doAction(Action goal,Object obj) {
        setState("i received");
        goal.doAction(obj);
        setState("i finished");
    }

    private string state;
    //setter getter state
} 

public class WorldTest implements Listener {

    @Test public void word{
    World  w= mock(World.class);
    w.addListener(this);
    ...
    ...

    }
}

interface Listener {
    void doAction();
}

答案

Mockito.doThrow(new Exception()).when(instance).methodName();
Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
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());
Mockito.doCallRealMethod().when(<objectInstance>).<method>();
<objectInstance>.<method>();
<Object> <objectInstance> = mock(<Object>.class, Mockito.CALLS_REAL_METHODS);
World world = new World();
World spy = Mockito.spy(world);
Mockito.doNothing().when(spy).methodToMock();
assertEquals(0,spy.methodToTestThatShouldReturnZero());

所谓问题的解决方案是使用spy Mockito.spy(...)而不是mock Mockito.mock(..)

间谍使我们能够进行部分嘲笑。 Mockito 擅长此事。由于您的班级不完整,因此您可以在该班级中模拟一些必需的位置。

import static org.mockito.Mockito.*;
private World world = spy(World.class);
doNothing().when(someObject).someMethod(anyObject());
doReturn("something").when(this.world).someMethod(anyObject());
@Test
public void testUpdate() {

    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] arguments = invocation.getArguments();
            if (arguments != null && arguments.length > 1 && arguments[0] != null && arguments[1] != null) {

                Customer customer = (Customer) arguments[0];
                String email = (String) arguments[1];
                customer.setEmail(email);

            }
            return null;
        }
    }).when(daoMock).updateEmail(any(Customer.class), any(String.class));

    // calling the method under test
    Customer customer = service.changeEmail("old@test.com", "new@test.com");

    //some asserts
    assertThat(customer, is(notNullValue()));
    assertThat(customer.getEmail(), is(equalTo("new@test.com")));

}

@Test(expected = RuntimeException.class)
public void testUpdate_throwsException() {

    doThrow(RuntimeException.class).when(daoMock).updateEmail(any(Customer.class), any(String.class));

    // calling the method under test
    Customer customer = service.changeEmail("old@test.com", "new@test.com");

}
}
doAnswer(new CallsRealMethods()).when(mock)
        .voidMethod(any(SomeParamClass.class));
doAnswer(Answers.CALLS_REAL_METHODS.get()).when(mock)
        .voidMethod(any(SomeParamClass.class));
doAnswer(i -> {
  // Do stuff with i.getArguments() here
  return null;
}).when(*mock*).*method*(*methodArguments*);
doAnswer(i -> {
  ((Runnable) i.getArguments()[0]).run();
  return null;
}).when(executor).execute(any());
Listener listener = mock(Listener.class);
w.addListener(listener);
world.doAction(..);
verify(listener).doAction();

可以通过两种方式完成此操作,具体取决于以下场景:

  1. doAnswer - 如果我们希望模拟的 void 方法做某事(尽管无效,也要模拟行为)。

  2. doThrow - 如果您想从模拟的 void 方法抛出异常,我们也有 Mockito.doThrow()。