1.报错
前一段时间想使用
@SpringBootTest
做测试,但是@Test
死活跑不了,网上找了很多办法都不能解决问题,今天打开电脑灵感乍现,突然想出了错误的根源。先看报错信息:
Error starting ApplicationContext.
To display the conditions report re-run your
application with 'debug' enabled.
21:56:47.074 [main] ERROR org.springframework.
boot.SpringApplication - Application run failed
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'XXX':
Injection of autowired dependencies failed;
nested exception is java.lang.IllegalArgumentException:
Could not resolve placeholder 'XXX' in value "XXX"
这段错误信息大概指的就是没法创建bean实例,为什么别人家的java源程序都能创建,你test就创不了呢?能不能像别人家的孩子一样有点出息?
2.问题原因
SpringBootTest加载不到配置文件,那么怎么解决呢?我尝试在网上找教程,有人说在pom.xml中加入<resources>
配置用于加载配置文件,但我尝试了,并没啥用。于是我仔细看了看我的application.yaml
文件,您猜怎么着:
没错,罪魁祸首就是test目录下的application-dev.yaml
,我相信你聪明的小脑袋瓜已经想到怎么回事了。
3.解决方案
解决方案1:将application-dev.yaml
改为application.yaml
,问题即可成功解决。
解决方案2:直接将test/resources/application.yaml
干掉也能成功运行。此时使用java/resources/application.yaml
。
4.题外话
SpringBootTest使用的时候要注意自己用的是JUnit5还是JUnit4。在SpringBoot2.2以前使用的是JUnit4,后面用的JUnit5。
4.1 JUnit4
在测试类上加入@RunWith(SpringRunner.class)
和@SpringBootTest
两个注解,测试方法上使用包比较短的那个:org.junit.@Test;
。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SBTest {
@Test
public void test01() {
System.out.println("1111111");
}
}
4.2 JUnit5
直接使用@SpringBootTest
和org.junit.jupiter.api.@Test
即可。
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class SBTest {
@Test
public void test01() {
System.out.println("1111111");
}
}