通过lambda验证模拟的方法调用吗?

时间:2019-04-19 12:41:33

标签: java unit-testing mocking mockito

使用Mockito,我想通过lambda验证模拟的方法调用(尤其是传递给它的参数),而不必使用Captor等。

我的事情

class MyThing {
  public void run() {
    // ... do stuff
    doSomething(someInt, someString);
  }

  public void doSomething(MyOtherThing otherThing) {
    // ... do more stuff
  }
}

MyThingTests

@Test
public void ensure_doSomething_does_something() {
  MyThing thing = mock(MyThing.class);

  doCallRealMethod().when(thing).run();
  thing.run();

  thing.doSomething(any(), any()).verify(otherThing -> {
    assertEquals(1, otherThing.getCount());
    assertEquals("abc", otherThing.getName());
  });
}

上面的测试是拦截对doSomething的调用并验证传入的参数。请注意,这需要对返回void的方法起作用。

我可能会使用doAnswer,但这似乎是一种hack,而不是它的意图。

0 个答案:

没有答案