将Spring Boot应用从Java重构为Kotlin时遇单元测试错误
Spring Boot从Java重构到Kotlin后单元测试报错的解决方法
问题场景
将Spring Boot应用从Java重构为Kotlin,已完成build.gradle的必要更新。Application类转为Kotlin后应用可正常运行,但构建时所有单元测试均抛出如下错误:
ProjectServiceTest > initializationError FAILED java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration. You need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test. at org.springframework.util.Assert.state(Assert.java:76) at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.findConfigurationClass(SpringBootTestContextBootstrapper.java:246) at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:233) at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:150) at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:351) at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:267) at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:215) at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108) at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:111)
对应的测试类代码:
@SpringBootTest public class AppserverApplicationTests { @Test public void contextLoads() { // do nothing } }
解决方法
核心原因
Spring测试框架无法找到带有@SpringBootConfiguration注解的配置类(即你的Kotlin版启动类),通常是包结构不匹配、启动类注解缺失或测试类未指定启动类导致。
指定启动类到@SpringBootTest
在测试类的@SpringBootTest注解中明确指定Kotlin版启动类:@SpringBootTest(classes = YourKotlinApplication.class) public class AppserverApplicationTests { @Test public void contextLoads() { // do nothing } }替换
YourKotlinApplication为实际的Kotlin启动类名称。对齐包结构
确保测试类与Kotlin启动类处于同一根包下,或者测试类的包是启动类包的子包。Spring Boot测试会自动扫描当前包及子包内的@SpringBootConfiguration类,包结构不一致会导致扫描失败。检查Kotlin启动类注解
确认Kotlin启动类上正确标注了@SpringBootApplication注解(该注解包含@SpringBootConfiguration):@SpringBootApplication class YourKotlinApplication fun main(args: Array<String>) { runApplication<YourKotlinApplication>(*args) }
内容的提问来源于stack exchange,提问作者Aditya Mishra
相关产品推荐
相关产品推荐

