How do Mockito matchers work?

前端 未结 2 1568
一整个雨季
一整个雨季 2020-11-21 23:43

Mockito argument matchers (such as any, argThat, eq, same, and ArgumentCaptor.capture()) behave very differe

2条回答
  •  自闭症患者
    2020-11-22 00:18

    Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

    If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

    when(foo.quux(anyInt(), anyInt())).thenReturn(true);
    when(foo.quux(anyInt(), eq(5))).thenReturn(false);
    

    is the order that ensures the (probably) desired result:

    foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
    foo.quux(2 /*any int*/, 5) //returns false
    

    If you inverse the when calls then the result would always be true.

提交回复
热议问题