【问题标题】:WebFluxTest cannot read matrix variablesWebFluxTest 无法读取矩阵变量
【发布时间】:2020-06-04 00:45:56
【问题描述】:

我正在写一个 WebFluxTest :

@WebFluxTest(controllers=Example.class)

class ExampleTest  {
    @Autowired
    WebTestClient webTestClient;
    @Test
    public void example(){

        webTestClient.get().uri("http://localhost:8080/example/employees/id=1")
                     .exchange()
                     .expectBody().consumeWith(response -> assertTrue(new String(response.getResponseBody(), StandardCharsets.UTF_8).contains(expected)));
    }
}

要测试的代码是:

@Controller
public class Example {

    @GetMapping("/example/employees/{id}")
    @ResponseBody
    public String example(@MatrixVariable("id") int id) {
        ....
    }

这是一个具有此配置的 Spring Boot 应用程序:

@Configuration
public class MyConfig implements WebMvcConfigurer {
   @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
...

输出是: "status":400,"error":"Bad Request","message":"int 类型的方法参数缺少矩阵变量 'id'"}

【问题讨论】:

  • 它可以帮助社区通过你的代码的作用来回答你的问题
  • 由于您只定义了要测试的 Example.class,它不会加载您的 bean,这是我的最佳猜测
  • 嗨,Thomas 和 Con,请在下面查看我自己的答案。我从 Spring 社区得到了一个很好的建议。问题是 @WebFluxTest 忽略了 WebMvcConfigurer。我需要改用@SpringBootTest。感谢您的帮助。

标签: spring-boot unit-testing spring-mvc spring-webflux


【解决方案1】:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
 @AutoConfigureWebTestClient
class Example {

    @LocalServerPort
    int port;

    @Test
    public void example (){
        WebTestClient webTestClient = WebTestClient.bindToServer()
                     .baseUrl("http://localhost:"+port+"/example /employees/id=1").build();
        String expected = String.format("Received request id = [%d]\n", 1);
        webTestClient.get().exchange()
                       .expectBody().consumeWith(response -> assertTrue(new String(response.getResponseBody(),
                                               StandardCharsets.UTF_8).contains(expected)));
    }

我询问了 Spring 社区。有人建议我不要使用 @WebFluxTest 来测试 mvc 控制器。我的 mvc 控制器不是 Web Flux 控制器。 此外,@WebFluxTest 会忽略 WebMvcConfigurer。 我需要像上面的代码一样加载整个 Spring boot 应用程序。

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多