Mokito:如何验证参数是否是具有特定参数的对象?

时间:2016-05-02 04:37:45

标签: java android unit-testing mockito

我有一个发布如下的EventBus

EventBus bus = EventBus.getDefault();
bus.post(new MyEvent("mystring", json));

我想执行单元测试以确保此总线使用MyEvent对象调用了post函数。

EventBus bus = mock(EventBus.class);
verify(bus).post(isA(MyEvent.class));

以上代码效果很好。但是,我还想确保在实例化期间将“mystring”传递给MyEvent对象。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:2)

要检查是否将某个具体对象传递给方法,可以使用Mockito @Captor

@RunWith(MockitoJUnitRunner.class)
public TestClass{

@Mock
private EventBus bus;

@Captor
private ArgumentCaptor<MyEvent> myEventCaptor;

@Test
public void testSaveAccount() {
    methodToTest();

    verify(bus).post(myEventCaptor.capture());
    MyEvent myEvent = myEventCaptor.getValue(); // last value that was captured
    assertThat(myEvent.getString, is("mystring"));
}