2 回答
TA贡献1900条经验 获得超5个赞
作为测试行为的一部分,测试异步行为通常不应涉及轮询以检查是否发生了某些事情。我建议隔离将异步运行的组件并“正常”单独测试它。然后,通过在响应前模拟异步组件一段固定的时间来测试将等待异步组件的组件。wait您可以使用它来测试所有相关情况下的等待组件:响应按预期出现、响应出现但它是一个错误、响应在超时之前从未出现等。
例如
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();
}
}
TA贡献1786条经验 获得超11个赞
Mockito 有一个功能可以解决这个问题,称为VerificationWithTimeout。我在我的代码中使用它来验证异步行为。这是 1000 毫秒超时时的样子:
@Mock WorkItem;
@Test
public void testSomething() throws Exception {
<do some testing>
ArgumentCaptor<WorkItemQuery> captor =
ArgumentCaptor.forClass(WorkItemQuery.class);
verify(WorkItem, timeout(1000)
.atLeastOnce()).call(captor.capture);
}
添加回答
举报