Mockito:轮询等待验证

@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循环?


慕侠2389804
浏览 106回答 2
2回答

梵蒂冈之花

作为测试行为的一部分,测试异步行为通常不应涉及轮询以检查是否发生了某些事情。我建议隔离将异步运行的组件并“正常”单独测试它。然后,通过在响应前模拟异步组件一段固定的时间来测试将等待异步组件的组件。wait您可以使用它来测试所有相关情况下的等待组件:响应按预期出现、响应出现但它是一个错误、响应在超时之前从未出现等。例如public interface AsyncObject {&nbsp; &nbsp; public void invoke();&nbsp; &nbsp; public Object check();}public class MyMockAsyncObject implements AsyncObject {&nbsp; &nbsp; private long delay;&nbsp; &nbsp; private long startTimeMillis;&nbsp; &nbsp; public MyMockAsyncObject(long delay) {&nbsp; &nbsp; &nbsp; &nbsp; this.delay = delay;&nbsp; &nbsp; }&nbsp; &nbsp; public void invoke() {&nbsp; &nbsp; &nbsp; &nbsp; startTimeMillis = now();&nbsp; &nbsp; }&nbsp; &nbsp; public Object check() {&nbsp; &nbsp; &nbsp; &nbsp; if (now() - startTimeMillis > delay) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Object();&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public class Waiter {&nbsp; &nbsp; public AsyncObject myAsyncObject;&nbsp; &nbsp; public Waiter(AsyncObject async) {&nbsp; &nbsp; &nbsp; &nbsp; this.myAsyncObject = async;&nbsp; &nbsp; }&nbsp; &nbsp; public Object getResult() {&nbsp; &nbsp; &nbsp; &nbsp; myAsyncObject.invoke();&nbsp; &nbsp; &nbsp; &nbsp; return this.waitForResult();&nbsp; &nbsp; }&nbsp; &nbsp; private Object waitForResult() {&nbsp; &nbsp; &nbsp; &nbsp; while(// is not timed out) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // wait a while&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myAsyncObject.check();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // return result if it's there&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; throw new Exception();&nbsp; &nbsp; }}

Qyouu

Mockito 有一个功能可以解决这个问题,称为VerificationWithTimeout。我在我的代码中使用它来验证异步行为。这是 1000 毫秒超时时的样子:@Mock WorkItem;@Testpublic void testSomething() throws Exception {&nbsp; &nbsp; <do some testing>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; ArgumentCaptor<WorkItemQuery> captor =&nbsp;&nbsp; &nbsp; ArgumentCaptor.forClass(WorkItemQuery.class);&nbsp; &nbsp; verify(WorkItem, timeout(1000)&nbsp; &nbsp; &nbsp; .atLeastOnce()).call(captor.capture);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java