前言
springboot提供了 spirng-boot-starter-test
以供开发者使用单元测试,在引入 spring-boot-starter-test
依赖后:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
其中包含以下几个库:
- Junit ——常用的单元测试库
- Spring Test & Spring Boot Test ——对Spring应用的集成测试支持
- AssertJ——一个断言库
- Hamcrest—— 一个匹配对象的库
- Mockito—— 一个Java模拟框架
- JSONassert—— 一个针对JSON的断言库
- JsonPath—— 用于JSON的XPath
下面我们将从Service层和Controller层的角度来简单介绍下单元测试
Service单元测试
在SpringBoot 2.0中,创建一个Service的单元测试,代码如下:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
public void insertUser() {
User user = new User();
user.setUsername("li ning");
user.setPassword("123456");
userService.insertUser(user);
}
}
上面的测试非常简单,主要需要注意两个注解: @RunWith
和@SpringBootTest
- @RunWith: 该注解标签是Junit提供的,用来说明此测试类的运行者,这里用了
SpringRunner
,它实际上继承了SpringJUnit4ClassRunner
类,而SpringJUnit4ClassRunner
这个类是一个针对Junit 运行环境的自定义扩展,用来标准化在Springboot环境下Junit4.x的测试用例 - @SpringBootTest 为 springApplication创建上下文并支持SpringBoot特性
使用@SpringBootTest
的webEnvironment
属性定义运行环境:
- Mock(默认): 加载WebApplicationContext 并提供模拟的web环境 Servlet环境,使用此批注时,不会启动嵌入式服务器
- RANDOM_PORT: 加载WebServerApplicationContext 并提供真实的web环境,嵌入式服务器,监听端口是随机的
- DEFINED_PORT: 加载WebServerApplicationContext并提供真实的Web环境,嵌入式服务器启动并监听定义的端口(来自 application.properties或默认端口 8080)
- NONE: 使用SpringApplication加载ApplicationContext 但不提供任何Web环境