gpt4 book ai didi

java - Mockito:轮询等待验证

转载 作者:行者123 更新时间:2023-12-02 09:44:48 30 4
gpt4 key购买 nike

@Mock WorkItem;

@Test(timeOut = 300000)
public void testSomething() throws Exception {
<do some testing>

verifyWorkDone()
}

public void verifyWorkDone() {
ArgumentCaptor<WorkItemQuery> captor =
ArgumentCaptor.forClass(WorkItemQuery.class);
verify(WorkItem, atLeastOnce()).call(captor.capture());
}

我想更改 verifyWorkDone() 的上述代码块,以便它继续重试验证,直到测试超时。

有什么好的方法可以实现这一点吗?只是抛出一个 while 循环?

最佳答案

测试异步行为通常不应该涉及轮询来检查测试行为中是否发生了某些事情。我建议隔离将异步运行的组件并“正常”地单独测试它。然后,通过模拟异步组件在响应之前等待固定的时间来测试将等待异步组件的组件。您可以使用它来测试所有相关情况下的等待组件:响应按预期出现、响应出现但出现错误、响应在超时之前从未出现等。

例如

public interface AsyncObject {
public void invoke();
public Object check();
}

public class MyMockAsyncObject implements AsyncObject {

private long delay;
private long startTimeMillis;

public MyMockAsyncObject(long delay) {
this.delay = delay;
}

public void invoke() {
startTimeMillis = now();
}

public Object check() {
if (now() - startTimeMillis > delay) {
return new Object();
} else {
return null;
}
}
}

public class Waiter {

public AsyncObject myAsyncObject;

public Waiter(AsyncObject async) {
this.myAsyncObject = async;
}

public Object getResult() {
myAsyncObject.invoke();
return this.waitForResult();
}

private Object waitForResult() {
while(// is not timed out) {
// wait a while
myAsyncObject.check();
// return result if it's there
}
throw new Exception();
}
}

关于java - Mockito:轮询等待验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56744660/

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