How to use ArgumentCaptor for stubbing?

前端 未结 3 913
礼貌的吻别
礼貌的吻别 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:15

    The line

    when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
    

    would do the same as

    when(someObject.doSomething(Matchers.any())).thenReturn(true);
    

    So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

    And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

提交回复
热议问题