背景:
项目需要写一个接口,该接口实现的方法时间较长。
interface Timeoutable {
public void longOperation();
}
困难:
测试代码是即时的,实际执行是异步的、缓慢的。
问题:
能否有这样的测试方法:测试接口是否在延迟范围内执行完
解决:
查了一下资料,mockito
框架还真有这方法。
public class AppTest {
private AutoCloseable closeable;
@BeforeEach
public void openMocks() {
closeable = MockitoAnnotations.openMocks(this);
}
@AfterEach
public void releaseMocks() throws Exception {
closeable.close();
}
@Mock
Timeoutable timeoutable;
private final Runnable asyncOperation = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
timeoutable.longOperation();
} catch (InterruptedException e) {
}
}
};
@Test
public void testMockitoConcurrentTimeoutSucceeds() {
new Thread(asyncOperation).start();
verify(timeoutable, timeout(2000)).longOperation();
new Thread(asyncOperation).start();
verify(timeoutable, timeout(3000).times(2)).longOperation();
}
}