How to use ArgumentCaptor for stubbing?

前端 未结 3 921
礼貌的吻别
礼貌的吻别 2020-11-27 11:51

In Mockito documentation and javadocs it says

It is recommended to use ArgumentCaptor with verification but not with stubbing.

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 12:23

    Assuming the following method to test:

    public boolean doSomething(SomeClass arg);
    

    Mockito documentation says that you should not use captor in this way:

    when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
    assertThat(argumentCaptor.getValue(), equalTo(expected));
    

    Because you can just use matcher during stubbing:

    when(someObject.doSomething(eq(expected))).thenReturn(true);
    

    But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

    ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
    verify(someObject).doSomething(argumentCaptor.capture());
    assertThat(argumentCaptor.getValue(), equalTo(expected));
    

提交回复
热议问题