Mockito和延期结果

问题描述 投票:3回答:3

我有一个基于spring的项目,我正在努力改进其中的代码覆盖率

我有以下代码块,它在defferedResult onCompletion方法上使用lambda

        util.getResponse(userInfoDeferredResult, url, userName, password);

    userInfoDeferredResult.onCompletion(() -> {
        //the result can be a String or ErrorResponse
        //if ErrorResponse we don't want to cause ClassCastException and we don't need to cache the result
        if (userInfoDeferredResult.getResult() instanceof String){

            String response = (String) userInfoDeferredResult.getResult();

            cacheServices.addValueToCache(Service.USER_INFO_CACHE_NAME, corpId, response);              
        }
    });

我想知道 - 是否可以使用mockito或powerMockito来模拟onCompletion lambda的内容?

java powermock spring-test powermockito
3个回答
6
投票

将内容提取到新方法:

if(userInfoDeferredResult.getResult() instanceof String) {
     String response = (String) userInfoDeferredResult.getResult();
     cacheServices.addValueToCache(Service.USER_INFO_CACHE_NAME, corpId, response);              
 }

然后用那种方法测试方法?


4
投票

您的测试应该模拟cacheServices,并执行lambda。


2
投票

在其他答案中提到的在这种情况下将内容提取到新方法是很好的解决方案。

此外,您可以在以下链接中找到文章:http://radar.oreilly.com/2014/12/unit-testing-java-8-lambda-expressions-and-streams.html

© www.soinside.com 2019 - 2024. All rights reserved.