我有一个基于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的内容?
将内容提取到新方法:
if(userInfoDeferredResult.getResult() instanceof String) {
String response = (String) userInfoDeferredResult.getResult();
cacheServices.addValueToCache(Service.USER_INFO_CACHE_NAME, corpId, response);
}
然后用那种方法测试方法?
您的测试应该模拟cacheServices,并执行lambda。
在其他答案中提到的在这种情况下将内容提取到新方法是很好的解决方案。
此外,您可以在以下链接中找到文章:http://radar.oreilly.com/2014/12/unit-testing-java-8-lambda-expressions-and-streams.html