junit启动报错 Unable to find a @SpringBootConfiguration

环境

springboot项目的junit测试

工程结构:

754c41c0625fe7f906df8c55d9730009a4b.jpg

test类代码如下:

0a22684bf504ae1901f237c87192768b9fe.jpg

 

问题

控制台中抛出如下异常:

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

75527fad9c6ce04794f50ee5b0c0fc145af.jpg

 

原因

项目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方法

503bd99a4a74803d957bb260eeb27a9af1e.jpg

转载于:https://my.oschina.net/u/1017791/blog/3024441

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值