spring boot 单元测试

本文介绍了如何在Spring Boot项目中配置单元测试,包括添加测试依赖、设置资源文件拷贝、注解使用及属性注入。在测试过程中,可能会遇到找不到配置文件或依赖注入失败的问题,文中给出了相应的解决办法,确保单元测试能够正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2.添加资源文件拷贝到target-test目录配置(pom.xml->biuld标签下)

<!--单元测试时引用src/main/resources下的资源文件-->
<testResources>
    <testResource>
        <directory>src/test/resources</directory>
    </testResource>
    <testResource>
        <directory>src/main/resources</directory>
    </testResource>
</testResources>

 

3.测试类上添加注解

@RunWith(SpringRunner.class)
@SpringBootTest

 

4.属性注入类使用

@PropertySource(value = "xx/xx.properties")类似的写法时,需要换成
@PropertySource("classpath:xx/xx.properties")

否则运行单元测试时,会报无法找到配置文件的错误

Could not open ServletContext resource [/application.yml]

 

5.如果报错:org.springframework.beans.factory.UnsatisfiedDependencyException:

则需要查看是否添加了@SpringBootTest注解

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值