首页 > 解决方案 > 使用 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 对象。任何帮助,将不胜感激。

标签: javaspringjunitmockitospring-webflux

解决方案


朋友不要让朋友嘲笑 Fluent API。

lambda 是内嵌的,因此无法单独测试。如果需要,则必须将其提取到可以测试的方法调用中。

  .flatMap( this::handleResponse )
  .block();
...
String handleResponse( Response empResponse ) {
  LOGGER.info(empResponse.getStatusCode());
  return empResponse.toEntity(String.class);
}

更一般地说,您可能希望查看Wiremock 之类的东西,它设置了一个本地网络服务器,您可以使用设置的测试响应作为种子。


推荐阅读