我正在编写一个selenium测试并使用mockito验证服务器行为.具体来说,当单击一个按钮时,我想确保页面控制器调用我所嘲笑的依赖项上的特定方法.
因为它是一个selenium测试,我需要等待在另一个线程中调用mock,所以我使用mockito timeout.
verify(myMock, timeout(5000).times(1)).myMethod("expectedArg");
我遇到的麻烦是myMethod被多次调用…而不是等待与预期参数匹配的调用,超时只等待第一次调用.
如果我使用Thread.sleep(50000)而不是超时(50000),它会按预期工作……但这很脏,所以我希望避免它.
如何使用预期输入等待myMethod?
解决方法:
如果您能够设置一定数量的预期调用,可以使用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"));
}
另一种方法是指定要验证的所有预期值,但这些值需要按照它们被调用的确切顺序提供.与上述解决方案的不同之处在于,即使使用一些未经验证的参数另外调用mock,这也不会失败.换句话说,无需知道总调用次数.代码示例:
@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");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。