1、简介
在日常开发中,我们经常需要对我们的代码进行输入输出进行测试,为了便捷测试,Springboot提供测试注解,帮助我们更加便捷实现测试。
2、Springboot测试中使用到的注解
2.1、@SpringBootTest注解使用
@SpringBootTest 替代了 Spring Test 中的 @ContextConfiguration 注解,目的是加载 ApplicationContext,启动 Spring 容器。在测试类中使用,需要注意以下两点:
1)、在使用 @SpringBootTest 时不用像 @ContextConfiguration 一样指定 locations 或 classes 属性,这是因为在 @SpringBootTest 注解上, 会自动检索程序的配置文件, 检索顺序是从当前包开始,逐级向上查找被 @SpringBootApplication 或 @SpringBootConfiguration 注解的类, 所以要求我们必须在测试文件目录(test/)下和这两个注解有相同的包路径。否则需要指定对应的类。
@SpringBootTest(classes = {TestMain.class})
2)、在 SpringBoot 项目中, 集成了 WebSocket,由于Websocket 是需要依赖 tomcat 等容器的启动, 而测试环境并没有真正的启动一个 tomcat 容器,启动会报错,解决办法是在 @SpringBootTest 里添加属性 webEnvironment = RANDOM_PORT。
@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
2.2、@RunWith注解
@RunWith(xx.class) 指定 Spring 的单元测试模块来执行标注了 @Test 注解的测试方法。
2.3、@Test 注解使用
@Test注解有两个版本,Junit4 和 Junit5,引入 spring-boot-strater-test 后 Junit4 和 Junit5 同时存在,两者在使用时有所不同,引入的包分别如下:
// Junit4
import org.junit.Test
// Junit5
import org.junit.jupiter.api.Test
注:Junit4 的 注解, 则需要加上 @RunWith(SpringRunner.class)一起使用,如果不加@RunWith注解,Spring容器不会启动。
2.3.1、Junit4
对于Junit4,通常使用如下注解 :
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestClass{
@Test
public void test(){}
}
2.3.2、Junit5
对于Junit5,通常使用如下注解:
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class TestClass{
@Test
public void test(){}
}
3、总结
本文介绍关于Springboot中测试使用方法以及遇到问题解决方式,关于如何进行MOCK接口进行测试将在后续进行详解。