【发布时间】: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