java - 使用 lambda 函数调用 rest api 的 Junit 测试用例
问题描述
考虑一个内部使用 lambda 函数的 rest api 调用方法,我们如何编写 junit 测试用例。我尝试了自己,但未能模拟在 post api 调用中表示为 lambda 函数的 uri 构建器。还有如何模拟 flatMap 中的块。下面给出了我尝试编写单元测试的代码片段。
public ResponseEntity<String> findEmployee(String empName, String empId) {
response = employeeService.post.uri(builder -> builder.path(pathMapper.get("GET_PATH")).queryParam(EMP_ID, empId).build())
.accept(APPLICATION.JSON)
.syncBody(empName)
.exchange()
.flatMap( empResponse -> {
LOGGER.info(empResponse.getStatusCode());
return empResponse.toEntity(String.class);
}).block();
return response;
}
其中,employeeService 是一个 Webclient 对象。任何帮助,将不胜感激。
解决方案
朋友不要让朋友嘲笑 Fluent API。
lambda 是内嵌的,因此无法单独测试。如果需要,则必须将其提取到可以测试的方法调用中。
.flatMap( this::handleResponse )
.block();
...
String handleResponse( Response empResponse ) {
LOGGER.info(empResponse.getStatusCode());
return empResponse.toEntity(String.class);
}
更一般地说,您可能希望查看Wiremock 之类的东西,它设置了一个本地网络服务器,您可以使用设置的测试响应作为种子。
推荐阅读
- matlab - 计数和分配给变量的提示
- ruby-on-rails - RSpec:ActionController::UrlGenerationError:用于自定义 url
- html - AngularJS select not showing selected value
- javascript - 在材质 ui 中使用 setState 设置当前日期
- matlab - 兰迪和兰特之间有什么联系?
- javascript - 为什么 1906 年以下的日期在解析时会错误地显示时间部分?
- javascript - d3渐变填充在Safari中显示黑色
- mysql - mysql:无法修改或更新日期值 0000-00-00 的列
- android - Ionic 3 如何知道 GPS 是否启用
- android - 首次运行应用程序时出错无法投射问题