我正在尝试用超时测试异步方法。
当我直接调用该方法时,该方法将异步运行并按预期抛出timeoutexception。但是当我存根该方法时,该方法会同步运行,并且不会抛出timeoutexception。我做错什么了?
Class A()
{
@Async
public Future<Integer> asyncMethod(){
Thread.sleep(5000);
return new AsyncResult<>(1);
}
}
Class B()
{
A a;
@Autowired
B(A a)
{
this.a=a;
}
public void syncMethod()
{
Future<Integer> futureResult = a.asyncMehod();
// 2sec < 5sec, expect to throw TimeoutException
futureCount.get(2, TimeUnit.SECONDS);
}
}
Class TestBMockBean()
{
@MockBean
A a;
B b;
@BeforeAll
public void init()}{
this.b = new B(a);
}
// This test failed
@Test
void syncMethod() {
when(a.asyncMethod()).thenAnswer((Answer<AsyncResult<Integer>>) invocation -> {
Thread.sleep(5000);
return new AsyncResult<>(0);
});
}
assertThrows(TimeoutException.class,()-> b.syncMethod());
}
}
Class TestBAutowired()
{
@Autowired
B b:
// This test pass
@Test //success
void syncMethod_autowired() {
assertThrows(TimeoutException.class,()-> b.syncMethod());
}
}
暂无答案!
目前还没有任何答案,快来回答吧!