WebFluxTest无法读取矩阵变量

问题描述 投票:0回答:1

我正在编写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);
    }
...

输出为:“状态”:400,“错误”:“错误的请求”,“消息”:“类型类型为int的方法参数缺少矩阵变量'id'”}

spring-boot unit-testing spring-mvc spring-webflux
1个回答
0
投票
@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)));
    }

我问春季社区。有人建议我不要使用@WebFluxTest来测试mvc控制器。我的mvc控制器不是Web流量控制器。另外,@ WebFluxTest会忽略WebMvcConfigurer。我需要以上面的代码加载整个Spring Boot应用程序。

© www.soinside.com 2019 - 2024. All rights reserved.