SpringBoot测试失败并报错: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration

2023年6月25日08:06:13

情况一:

该测试类在测试包test下的包名和类路径java下的包名不一致导致的,修改包名一致即可
SpringBoot测试失败并报错: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration
由于包名自动生成的缘故导致这两个包名不一致,引发以下报错

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

解决:修改包名一致,如图
SpringBoot测试失败并报错: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration
问题解决,这是最好的解决方案

情况二

如果不想修改包名,那么需要在注解上加上@SpringBootTest(classes = xxx.class),来告诉springboot这是一个独立的测试类,注意xxx代表测试方法的类名,如图所示
SpringBoot测试失败并报错: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration
但这里会产生额外的问题,因为此时springboot已经把该类当成一个独立的测试类了,这意味着这个测试类对应独立的IOC容器,所以此时我们无法注入到main包中的组件,案例如下,main包下的路径是com.sobot.demo7,而同理,test包下com.sobot.demo7路径下测试类,可以正常装配userMapper组件

com.sobot.demo8路径下测试类,则根本无法找到userMapper这个组件
SpringBoot测试失败并报错: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration
这种情况下测试类DemoApplicationTests中无法注入com.sobot.demo7路径下的组件userMapper

情况三

使用以下注解

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JPAConfig.class})

  • 作者:垃圾王子晗
  • 原文链接:https://blog.csdn.net/wwwwwww31311/article/details/115461920
    更新时间:2023年6月25日08:06:13 ,共 712 字。