java - Mockito:WAITING与参数匹配的调用

标签 java testing selenium asynchronous mockito

我正在编写一个 selenium 测试并使用 mockito 验证服务器行为。具体来说,当单击按钮时,我想确保页面 Controller 调用我已模拟的依赖项上的特定方法。

因为是 selenium 测试,我需要等待 mock 在另一个线程中被调用,所以我使用了 mockito 超时。

verify(myMock, timeout(5000).times(1)).myMethod("expectedArg");

我遇到的问题是 myMethod 被多次调用......而不是等待与预期参数匹配的调用,超时只等待第一次调用。 如果我使用 Thread.sleep(50000) 而不是 timeout(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"));
}

另一种方法是指定要验证的所有预期值,但需要按照调用它们的确切顺序提供这些值。与上述解决方案的不同之处在于,即使使用一些未经验证的参数额外调用了模拟,这也不会失败。换句话说,不需要知道总调用次数。代码示例:

@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");
}

关于java - Mockito:WAITING与参数匹配的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22944202/

相关文章:

java - 无法使用 Selenium WebDriver (Firefox) 与输入(角色=组合框)交互

java - GPS 位置更改时如何将 Android 应用程序返回前台

.net - TFS 2010 中的功能测试

python - 使用 Selenium Web 驱动程序提取我想要的值时遇到问题

python - 使用Python通过selenium Webdriver中的Url上传图像

java - 使用 EMMA 获取 ClassFormatError?

java - 如何使用正则表达式查找字符串是否至少有一个字符?

javascript - sinon.stub().returns 为每次调用而不是一次指定

testing - Codeception 添加新的 JsonTypes

java - TestNG retryAnalyzer 仅在方法@Test 中定义时才有效,在类'@Test 中无效