junit - 使用 WebTestClient 和 ControllerAdvice 单元测试 Spring Controller

标签 junit spring-test spring-restcontroller spring-webflux

我正在尝试对我的 Controller 和特定情况进行单元测试:我的服务返回一个 Mono.Empty,我抛出一个 NotFoundException 并且我不想确保我收到 404 异常

这是我的 Controller :

@GetMapping(path = "/{id}")
    public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) throws NotFoundException {

        return this.myService.getObject(id, JsonNode.class).switchIfEmpty(Mono.error(new NotFoundException()));

    }

这是我的 Controller 建议:
@ControllerAdvice
public class RestResponseEntityExceptionHandler {

    @ExceptionHandler(value = { NotFoundException.class })
    protected ResponseEntity<String> handleNotFound(SaveActionException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
    }

}

和我的测试:
@Before
    public void setup() {
        client = WebTestClient.bindToController(new MyController()).controllerAdvice(new RestResponseEntityExceptionHandler()).build();
    }
@Test
    public void assert_404() throws Exception {

        when(myService.getobject("id", JsonNode.class)).thenReturn(Mono.empty());

        WebTestClient.ResponseSpec response = client.get().uri("/api/object/id").exchange();
        response.expectStatus().isEqualTo(404);

    }

我收到 NotFoundException 但是 500 错误不是 404 这意味着我的建议没有被调用

堆栈跟踪 :
java.lang.AssertionError: Status expected:<404> but was:<500>

> GET /api/fragments/idFragment
> WebTestClient-Request-Id: [1]

No content

< 500 Internal Server Error
< Content-Type: [application/json;charset=UTF-8]

Content not available yet

任何的想法 ?

最佳答案

我相信你可以删除这个 Controller 建议,只需要以下内容:

    @GetMapping(path = "/{id}")
    public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) {

        return this.myService.getObject(id, JsonNode.class)
                             .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));

    }

至于ResponseEntityExceptionHandler ,这个类是 Spring MVC 的一部分,所以我认为你不应该在 WebFlux 应用程序中使用它。

关于junit - 使用 WebTestClient 和 ControllerAdvice 单元测试 Spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44881722/

相关文章:

java - 无需应用程序测试 Spring/Spring Boot

java - ClassReader 中的 ArrayIndexOutOfBoundsException 导致加载 ApplicationContext 失败

java - JUnit:为测试类设置事务边界

spring-boot - Angular 5 : Sending POST request with string parameters and FormData parameter together, 到 Spring REST Controller

java - 在 JUnit 中,如何跳过当前步骤中的其余测试方法并继续下一步?

maven - 如何为 Surefire Maven 插件指定 JUnit 自定义运行器?

Spring @RequestBody REST 服务 post 方法在某些实体关系中返回 415

java - 在 @RestController 中使用嵌套对象进行 GET 请求?

Java 7 cobertura 代码分支覆盖字符串 switch 语句

java - SpringJUnit4ClassRunner 中的 spring @Conditional