Example of Mockito's argumentCaptor

后端 未结 4 1153
我在风中等你
我在风中等你 2020-12-04 07:21

Can anyone please provide me an example showing how to use the org.mockito.ArgumentCaptor class and how it is different from simple matchers that are p

4条回答
  •  一向
    一向 (楼主)
    2020-12-04 07:42

    The two main differences are:

    • when you capture even a single argument, you are able to make much more elaborate tests on this argument, and with more obvious code;
    • an ArgumentCaptor can capture more than once.

    To illustrate the latter, say you have:

    final ArgumentCaptor captor = ArgumentCaptor.forClass(Foo.class);
    
    verify(x, times(4)).someMethod(captor.capture()); // for instance
    

    Then the captor will be able to give you access to all 4 arguments, which you can then perform assertions on separately.

    This or any number of arguments in fact, since a VerificationMode is not limited to a fixed number of invocations; in any event, the captor will give you access to all of them, if you wish.

    This also has the benefit that such tests are (imho) much easier to write than having to implement your own ArgumentMatchers -- particularly if you combine mockito with assertj.

    Oh, and please consider using TestNG instead of JUnit.

提交回复
热议问题