gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:51:32 26 4
gpt4 key购买 nike

我正在编写一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com