繁体   English   中英

如何在 spring-webflux WebTestClient 测试中验证异常?

[英]How to validate Exception in spring-webflux WebTestClient tests?

如何验证spring-webflux测试中的实际Exception 以下在旧的spring-web环境中工作,但迁移到 netty 和 spring-webflux, MvcResult无法再解析( NullPointerException ):

@SpringBootTest
@AutoConfigureWebTestClient
public class ApiTest {
    @Test
    public void test() throws Exception {
        webTestClient.get()
                .uri("/api?test=123")
                .exchange()
                .expectStatus().isBadRequest()
                .expectBody().consumeWith(rsp -> {
                     //throws NPE
                    Exception ex = ((MvcResult) rsp.getMockServerResult()).getResolvedException();
                    assertTrue(ex instanceof ResponseStatusException);
                });
    }
}

@RestController 
public class ApiController {
   @PostMapping("/api")
   public String test(@RequestParam String test) {
      if (test.matches("[0-9]+"))
         throw new ResponseStatusException(HttpStatus.BadRequest, "Prohibited characters");
   }   
}

我怎样才能验证真正的异常类?

WebTestClient的主要目的是使用 fluent API 测试端点以验证响应。 没有神奇的反序列化或错误处理发生,但您可以访问原始响应(状态、标题、正文)。

在您的示例中,您不会获得MvcResultResponseStatusException但您可以使用rsp.getResponseBody()访问原始正文,看起来像

{
    "timestamp": "2022-05-17T17:57:07.041+00:00",
    "path": "/api",
    "status": 400,
    "error": "Bad Request",
    "requestId": "4fa648d"
}

您可以使用expectBody().consumeWith(rsp -> { ... })来访问请求和响应,或者使用 expectBody(String.class).value(body -> { ... }) to get just body. As an alternative use some fluent API to validate result JSON to get just body. As an alternative use some fluent API to validate result JSON .expectBody().json() or .expectBody().jsonPath()` 以仅检查特定字段。

此外,您仍然可以使用.expectBody(Response.class).value(body -> {...})显式反序列化 body。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM