@SpringBootTest碰到的坑(别人没发过的坑)

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
删除掉test单独的配置

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

直接使用@SpringBootTestorg.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");
    }
}
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hidelw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值