我有一个异步方法,我正在使用倒计时锁存器转换为同步方法。我在努力编写单元测试而不使用mockito的超时功能。我无法弄清楚如何让验证方法等待异步方法调用:
public interface SyncExchangeService {
boolean placeOrder(Order order);
}
public interface ExchangeService {
void placeOrder(Order order, OrderCallback orderResponseCallback);
}
public interface OrderCallback {
public void onSuccess();
public void onFailure();
}
public class SyncExchangeServiceAdapter implements SyncExchangeService {
private ExchangeService exchangeService;
public SyncExchangeServiceAdapter(ExchangeService exchangeService) {
this.exchangeService = exchangeService;
}
@Override
public boolean placeOrder(Order order) {
final CountDownLatch countdownLatch=new CountDownLatch(1);
final AtomicBoolean result=new AtomicBoolean();
exchangeService.placeOrder(order, new OrderCallback() {
@Override
public void onSuccess() {
result.set(true);
countdownLatch.countDown();
}
@Override
public void onFailure(String rejectReason) {
result.set(false);
countdownLatch.countDown();
}
});
try {
countdownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return result.get();
}
}
public class SyncExchangeServiceAdapterTest {
private ExchangeService mockExchange=mock(ExchangeService.class);
private SyncExchangeServiceAdapter adapter=new SyncExchangeServiceAdapter(mockExchange);
private Boolean response;
private ArgumentCaptor<Boolean> callback=CaptorArgumentCaptor.forClass(OrderCallback.class);
private CountDownLatch latch=new CountDownLatch(1);
@Test
public void testPlaceOrderWithSuccess() throws Exception {
final Order order=mock(Order.class);
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
response=adapter.placeOrder(order);
latch.countDown();
}
});
verify(mockExchange,timeout(10) ).placeOrder(eq(order), callbackCaptor.capture());
//the timeout method is not really recommended and could also fail randomly if the thread takes more than 10ms
callbackCaptor.getValue().onSuccess();
latch.await(1000,TimeUnit.MILLISECONDS);
assertEquals(true,response);
}
}
答案 0 :(得分:2)
对于这些类型的测试,我喜欢使用一个名为awaitility的小库。您可以使用倒计时锁定器自己完成,但正如您所看到的那样,您必须使用弯刀来修复您的测试才能完成这项工作。
在此测试中,您应在等待锁定后调用验证。
代码中的另一个问题是private Boolean response
。由于您要在另一个主题中更改它,因此您应该将其设为AtomicBoolean
或至少声明为volatile
。
答案 1 :(得分:-1)
我不确定我是否正确理解你。如果你想测试一个线程无限期等待,直到其他线程做某事,那么我会说你不能这样做。因为这意味着你在询问程序是否终止。相反,你可以做两件事。