在这种情况下,尽管我只需要捕获第一个参数,但我是否需要为每个参数编写一个捕获器?
durron597 的回答 https://stackoverflow.com/a/32719372/1426891是正确的——您不需要capture如果您想捕获其中一个参数,则可以使用所有参数。不过,需要澄清一点:致电ArgumentCaptor.capture()
算作 Mockito 匹配器,在 Mockito 中,如果您使用matcher对于任何方法参数你必须对所有参数使用匹配器 https://stackoverflow.com/q/22822512/1426891.
对于一个方法yourMock.yourMethod(int, int, int)
and an ArgumentCaptor<Integer> intCaptor
:
/* good: */ verify(yourMock).yourMethod(2, 3, 4); // eq by default
/* same: */ verify(yourMock).yourMethod(eq(2), eq(3), eq(4));
/* BAD: */ verify(yourMock).yourMethod(intCaptor.capture(), 3, 4);
/* fixed: */ verify(yourMock).yourMethod(intCaptor.capture(), eq(3), eq(4));
这些也有效:
verify(yourMock).yourMethod(intCaptor.capture(), eq(5), otherIntCaptor.capture());
verify(yourMock).yourMethod(intCaptor.capture(), anyInt(), gt(9000));