Mockito与Java async-> sync转换器

DD.*_*DD. 8 java asynchronous mockito

我有一个异步方法,我正在使用倒计时锁存器转换为同步方法.我在努力编写单元测试而不使用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);
    }


}
Run Code Online (Sandbox Code Playgroud)

iwe*_*ein 3

对于此类测试,我喜欢使用一个名为waitility的小库。您可以使用倒计时闩锁自己完成此操作,但正如您所看到的,您必须用砍刀修改测试才能使其工作。

在此测试中,您应该在等待锁存器后调用 verify。

您的代码中的另一个问题是private Boolean response. 由于您要在另一个线程中更改它,因此您应该将其设为AtomicBoolean或至少声明它volatile