我有一个异步方法,我正在使用倒计时锁存器转换为同步方法。我在不使用 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);
}
}