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注解