stubing@async方法作为sync运行

mgdq6dx1  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(166)

我正在尝试用超时测试异步方法。
当我直接调用该方法时,该方法将异步运行并按预期抛出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());
  }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题