环境java
springboot项目的junit测试spring
工程结构:springboot
test类代码以下:测试
问题spa
控制台中抛出以下异常:3d
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your testblog
缘由ci
项目SpringBoot启动类路径为com.eddue.datav下与测试类com.eddue.biz不一致。由于@SpringBootTest会自动查询@SpringBootConfiguration,在com.eddue.biz类路径下搜索@SpringBootConfiguration。然而java源代码的类路径为com.eddue.datav下的ServerApplication的@SpringBootApplication中引用了@SpringBootConfiguration,这里才有@SpringBootConfiguration注解。所以致使没法查询到@SpringBootConfiguration注解,致使没法加载springboot启动类ServerApplication。it
参考SpringBootTest下类注释io
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方法