使用WebTestClient和ControllerAdvice对Spring控制器进行单元测试

5
我是一名可以帮助翻译的助手。这段需要翻译的内容涉及IT技术,主要是关于单元测试控制器的特定情况。在这种情况下,我的服务返回一个Mono.Empty对象,我抛出了一个NotFoundException异常,并且我想确保我得到了一个404异常。以下是我的控制器代码:
@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()));

    }

这是我的控制器建议:

@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

有什么想法吗?
1个回答

2

我认为您可以删除此控制器建议并只使用以下内容:

    @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应用程序中使用它。


嗨,谢谢你的回复。实际上,我找到了使用WebFlux的ControllerAdvice的示例,所以我认为我应该能够使用它。 - Seb
很好。有了ResponseEntityExceptionHandler意味着您可能在类路径上有spring-webmvc(您不应该这样做)。您能否尝试从项目中删除该依赖项并不继承ResponseEntityExceptionHandler - Brian Clozel
你能分享一下堆栈跟踪吗? - Brian Clozel
堆栈跟踪中没有太多信息,但我仍然将其添加到帖子中。 - Seb
我指的是服务器应用程序的堆栈跟踪(如果有的话)。在运行应用程序并发送curl请求时,这是否有效(即不使用测试基础结构)? - Brian Clozel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接