配置spring.main.web-application-type=NONE仍加载GenericWebApplicationContext问题
问题根因
@SpringBootTest 注解的web环境探测逻辑优先级高于application.yml中的spring.main.web-application-type配置,所以配置文件的设置会被注解的默认逻辑覆盖。@SpringBootTest默认会根据classpath下的web相关依赖自动判断是否启动web上下文,只要项目中引入了web依赖,默认就会加载GenericWebApplicationContext。
修复步骤
第一步(官方推荐方案):直接在
@SpringBootTest注解中显式指定非web环境
代码示例:@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) class YourTimedTaskTest { // 编写测试逻辑 }该配置会直接通知Spring Boot测试框架不要启动任何web相关上下文,优先级高于所有配置文件设置,配置后默认不会触发Servlet相关初始化逻辑。
第二步(可选,若第一步后仍触发ServletTestExecutionListener):显式排除Servlet相关测试监听器
增加@ExcludeTestExecutionListeners注解直接过滤Servlet测试处理器,从执行链层面禁止相关逻辑运行:@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @ExcludeTestExecutionListeners(ServletTestExecutionListener.class) class YourTimedTaskTest { // 编写测试逻辑 }该配置会完全阻止
ServletTestExecutionListener的执行,自然不会创建MockServletContext实例。全局生效方案:如果需要对所有测试统一禁用web环境,可以在测试资源目录下新建
spring.properties文件,添加配置:spring.test.web.mock.enabled=false该配置会全局关闭Spring Boot测试的Mock Web环境自动装配逻辑。
验证标准
启动测试后查看上下文实现类,正常应为AnnotationConfigApplicationContext而非GenericWebApplicationContext,同时日志中不会出现Servlet初始化、MockServletContext创建的相关记录,Oauth2组件会按非Servlet环境的逻辑运行。
内容的提问来源于stack exchange,提问作者Vincent F

