繁体   English   中英

在Java中使用Redis async命令对void方法进行单元测试

[英]Unit testing a void method with Redis async command in java

我正在尝试为以下功能编写单元测试。

responseHandlerErrorHandler都是使用命令模式传递的方法,用于继续程序的流程。 futureCommand是一个生菜对象(Java中的Redis实现)。 我在测试此方法时遇到了困难,因为这既使用了Future,也不返回任何内容。

public void getOfferData(EventRequestContext<? extends BaseEvent> ctx, int offerId, ResponseHandler<T1Offer> responseHandler,
        ErrorHandler<Throwable> errorHandler) throws Exception {
    String redisKey = keyPrefix + offerId;
    RedisFuture<List<String>> futureCommand = connectionWrapper.getHashValues(redisKey, getRequiredParams());
    futureCommand.thenAccept(valuesList -> {
        TrackerScheduler.processT1GenreicPool.execute(ctx, () -> {
            Map<String, String> resultMap = reconstructMapValues(valuesList, getRequiredParams(), redisKey, ctx);
            T1Offer offerData;
            if(!resultMap.isEmpty()) {
                offerData = new T1Offer(resultMap);
            } else {
                offerData = new T1Offer();
            }
            if(!offerData.isValid()) {
                errorHandler.onError(new Exception("Invalid fields in offerData"));
            } else {
                responseHandler.onResponse(offerData);
            }
        });
    });
}

我最好的尝试是使用responseHandler方法发送断言,如下所示:

@Test
public void getOfferData_offerFullData_parseSuccess() throws Exception {
    T1ClickOfferDao.instance.getOfferData(null, Integer.parseInt(OFF_ID), resultOffer -> { 
        Assert.assertEquals("", resultOffer.getActivationDate());
    }, error -> {
    });
}

但在评估未来之前,测试上下文已完成。 即使我Threas.sleep一秒钟-断言也不会影响测试结果。

怎么样

@Test
public void getOfferData_offerFullData_parseSuccess() throws Exception {
    final String lock = new String("lock");
    T1ClickOfferDao.instance.getOfferData(null, Integer.parseInt(OFF_ID), resultOffer -> { 
        Assert.assertEquals("", resultOffer.getActivationDate());
        synchronized(lock){
            lock.notifyAll();
        }
    }, error -> {
    });
    synchronized(lock){
        try{ 
            lock.wait(1000*2); 
        } catch (InterruptedException ex) {
            fail("Timeout");
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM