SpringBoot使用测试类进行测试实践
作者:爱学习的大雄
SpringBoot测试类配置指南,介绍如何引入junit和springboot测试依赖,使用@SpringBootTest注解,并通过读取配置文件注入属性,确保测试运行无误
SpringBoot使用测试类进行测试
在复习springboot的过程中忘记了测试类该如何去配置运行,经过查阅以前的资料以及网络资料,整合如下。
实现
引入依赖
junit依赖和springboot的test依赖,我这里没有标明版本
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>编写测试类
这里需要注意,@RunWith和@SpringBootTest一定不能忘记了,否则不能测试运行springboot项目的
这里的user中的值采用的是读取配置文件中的值的方式注入属性,可以不用管
//@RunWith:表示启动这个单元测试类(单元测试类是不能够运行的),需要传递一个参数,必须是SpringRunner实例类型
@RunWith(SpringRunner.class)
//@SpringBootTest:标注当前的类是一个测试类,不会随同项目一块打包,classes为你项目的启动类
@SpringBootTest(classes = SpringBoot_1_Application.class )
public class Test1 {
@Autowired
private User user;
@Test
public void tt(){
System.out.println(user);
}
}
测试

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
