如果您能够将固定数量的呼叫设置为预期,则可以使用以下命令完成:ArgumentCaptor
import static org.hamcrest.CoreMatchers.hasItem;
@Captor ArgumentCaptor<String> arg;
@Before
public void setUp() throws Exception {
// init the @Captor
initMocks(this);
}
@Test
public void testWithTimeoutCallOrderDoesntMatter() throws Exception {
// there must be exactly 99 calls
verify(myMock, timeout(5000).times(99)).myMethod(arg.capture());
assertThat(arg.getAllValues(), hasItem("expectedArg"));
}
另一种方法是指定要验证的所有预期值,但这些值需要按照调用它们的确切顺序提供。与上述解决方案的不同之处在于,即使使用一些未经验证的参数另外调用了模拟,这也不会失败。换句话说,无需知道总调用次数。代码示例:
@Test
public void testWithTimeoutFollowingCallsDoNotMatter() throws Exception {
// the order until expected arg is specific
verify(callback, timeout(5000)).call("firstExpectedArg");
verify(callback, timeout(5000)).call("expectedArg");
// no need to tell more, if additional calls come after the expected arg
// verify(callback, timeout(5000)).call("randomArg");
}