Intellij中KotlinTest引发Thymeleaf大量异常问题求助
我最近在IntelliJ里用Kotlin开发Spring Boot项目,搭的是Spring MVC+Thymeleaf的组合,之前跑应用一切正常,但跑测试的时候踩了个坑:哪怕测试完全和Thymeleaf没关系,只是实例化测试类,都会触发Thymeleaf抛出一堆模板相关的异常。
我已经做了个最小复现的项目,这里贴两种测试代码的示例:
测试代码1:仅加载Spring上下文的基础测试
@SpringBootTest class DemoApplicationTests { @Test fun contextLoads() { // 空测试,只是验证上下文能加载 } }
测试代码2:仅针对服务层的轻量化测试
@ExtendWith(SpringExtension::class) @SpringBootTest(classes = [DemoService::class]) class DemoServiceTest { @Autowired lateinit var demoService: DemoService @Test fun testService() { assertEquals("Hello", demoService.greet()) } }
不管跑哪一种,都会弹出类似这样的Thymeleaf异常:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
...(后续异常堆栈信息)
几种可行的解决办法
1. 测试时排除Thymeleaf自动配置
如果你的测试根本不需要视图层支持,直接在@SpringBootTest里排除Thymeleaf的自动配置类,这样Spring就不会初始化Thymeleaf相关的Bean:
@SpringBootTest(exclude = [ThymeleafAutoConfiguration::class]) class DemoServiceTest { // 你的测试代码 }
2. 使用更细分的测试注解(Spring Boot 3.1+)
要是你只是测服务层或者数据层,推荐用Spring Boot 3.1及以上版本提供的@ServiceTest、@DataJpaTest这类专门的测试注解——它们只会初始化对应业务层的Bean,完全不会碰Web和视图层的配置:
@ServiceTest class DemoServiceTest { @Autowired lateinit var demoService: DemoService @Test fun testService() { assertEquals("Hello", demoService.greet()) } }
3. 关闭测试环境的Thymeleaf模板检查
如果必须保留完整的Spring上下文,但不想因为模板不存在报错,可以在测试专用的配置文件application-test.properties里加一行配置,关闭模板路径检查:
spring.thymeleaf.check-template-location=false
问题根源
默认情况下,@SpringBootTest会加载完整的应用上下文,只要你的依赖里有Thymeleaf,Spring Boot就会自动初始化它的模板解析器、视图解析器等组件。这些组件在初始化时会验证模板路径或者尝试预加载模板,一旦找不到对应模板就会抛出异常——哪怕你的测试完全用不上这些组件。
内容的提问来源于stack exchange,提问作者UncleBob

