环境
springboot项目的junit测试
工程结构:
test类代码如下:
问题
控制台中抛出如下异常:
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
原因
项目SpringBoot启动类路径为com.eddue.datav下与测试类com.eddue.biz不一致。因为@SpringBootTest会自动查询@SpringBootConfiguration,在com.eddue.biz类路径下搜索@SpringBootConfiguration。然而java源代码的类路径为com.eddue.datav下的ServerApplication的@SpringBootApplication中引用了@SpringBootConfiguration,这里才有@SpringBootConfiguration注解。因此导致无法查询到@SpringBootConfiguration注解,导致无法加载springboot启动类ServerApplication。
参考SpringBootTest下类注释
Automatically searches for a @SpringBootConfiguration when nested @Configuration is not used, and no explicit classes are specified.
意思是:会自动搜寻一个@SpringBootConfiguration,当不使用嵌套@Configuration,也没有明确指定类
解决方案
下面提供两种解决方案,选择其中任一方案即可
1:修改工程结构,将测试类路径com.eddue.biz改为com.eddue.datav,使自动扫描能查询到。
2:修改测试类代码,将测试类代码@SpringBootTest改为@SpringBootTest(classes = ServerApplication.class),手动指定springboot启动类路径。
测试结果
两种解决方案都能正常加载springboot启动,并正常运行junit的test方法