为何@EnableAutoConfiguration与@WebMvcTest无法兼容?
关于@WebMvcTest需手动导入自动配置类的问题
使用@WebMvcTest测试Spring Cloud Gateway MVC的路由功能时,必须通过@Import手动导入所需的自动配置类,否则测试上下文会缺少必要的Bean。
可行实现示例
以下代码通过显式导入相关自动配置类,可正常完成测试:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.servlet.function.RouterFunction; import org.springframework.web.servlet.function.ServerResponse; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(controllers = MyWebMvcTest.ComplimentingConfig.class) @Import({GatewayServerMvcAutoConfiguration.class, SslAutoConfiguration.class, RestClientAutoConfiguration.class}) public class MyWebMvcTest { @Autowired MockMvc mockMvc; @Test void test() throws Exception { mockMvc.perform(get("/get")) .andExpect(status().isOk()); } @Configuration static class ComplimentingConfig { @Bean public RouterFunction<ServerResponse> getRoute() { return route() .GET("/get", http("https://httpbin.org/status/200")) .build(); } } }
错误尝试及异常
若改为导入标注@EnableAutoConfiguration的配置类,试图隐式包含所需配置,会抛出Bean缺失异常:
修改后的测试类代码片段
@WebMvcTest(controllers = MyWebMvcTest.ComplimentingConfig.class) @Import(MyWebMvcTest.ComplimentingConfig.class) public class MyWebMvcTest { // ... @Configuration @EnableAutoConfiguration static class ComplimentingConfig {
抛出的异常信息
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.gateway.server.mvc.handler.ProxyExchangeHandlerFunction' available
使用环境
- Java 17
- Spring MVC 6.1.5
- Spring Boot 3.2.4
补充说明
该问题仅在使用Spring Cloud Gateway MVC的路由功能时出现,若使用普通RouterFunction,@WebMvcTest会自动提供所有必要Bean,无需额外导入配置类。
内容的提问来源于stack exchange,提问作者Powet
相关产品推荐
相关产品推荐

