Spring Test与JUnit结合起来提供了高效便捷的测试解决方案,而Spring Boot Test是在Spring Test之上增加了切片测试并增强了Mock能力。
Spring Boot Test支持的测试种类,主要分为以下三类:
- 单元测试,面向方法的测试,常用注解有@Test
- 功能测试,面向业务的测试,同时也可以使用切面测试中的Mock能力,常用的注解有@RunWith,@SpringBootTest等
- 切片测试,面向难于测试的边界功能,介于单元测试和功能测试之间,常用注解有@RunWith,@WebMvcTest等
测试过程中的关键要素及支撑方式如下:
- 测试运行环境,通过@RunWith和@SpringBootTest启动Spring容器
- Mock能力,Mockito提供Mock能力
- 断言能力,AssertJ、Hamcrest、JsonPath提供断言能力
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServerTestApplication {
public static void main(String[] args) {
SpringApplication.run(MyServerTestApplication.class, args);
}
}
在Spring Boot中开启测试只需要引入spring-boot-starter-test依赖,使用@RunWith和@SpringBootTest注解就可以开始测试。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
引入spring-boot-starter-test后,相关的测试依赖的类库也将一起依赖进来
- JUnit,Java测试的标准,默认依赖版本是4.12(JUnit5和JUnit4差别较大)
- Spring Test & Spring Boot Test,测试支持
- AssertJ,提供了流式的断言方式
- Hamcrest,提供了丰富的matcher,库的匹配对象(也称为约束或谓词)
- Mockito,Mock框架,可以按类型创建Mock对象,可以根据方法参数指定特定的响应,也支持对于Mock调用过程的断言
- JSONassert,为JSON提供断言功能
- JsonPath,为JSON提供XPATH功能
单元测试
public class UserServiceTest extends MyServerTestApplication {
@Autowired
private IUserService userService;
@Test
public void testAddUser() {
userService.add(buildUser("Jack", 18));
}
private User buildUser(String username, int age) {
User user = new User();
user.setUsername(username);
user.setAge(age);
return user;
}
}
- @RunWith是JUnit4提供的注解,将Spring和JUnit连接起来
- @SpringBootTest替代了Spring-Test中的@ContextConfiguration注解,目的是加载ApplicationContext,启动Spring容器,且SpringBootTest会自动检索配置文件,检索顺序是从当前包开始,逐级向上查找被@SpringBootApplication或@SpringBootConfiguration注解的类
功能测试
使用@SpringBootTest后,Spring将加载所有被管理的Bean,基本等同于启动了整个服务,测试就可以进行功能测试
由于Web是最常见的服务,@SpringBootTest注解中也给出了四种Web的Environment参数设置
public static enum WebEnvironment {
MOCK(false),
RANDOM_PORT(true),
DEFINED_PORT(true),
NONE(false);
private final boolean embedded;
private WebEnvironment(boolean embedded) {
this.embedded = embedded;
}
public boolean isEmbedded() {
return this.embedded;
}
}
- Mock,默认值,提供一个Mock环境,可以和@AutoConfigureMockMvc或@AutoConfigureWebTestClient搭配使用,开启Mock的相关功能,此时内嵌的服务并没有真正启动,也不会监听Web服务端口
- RANDOM_PORT,启动一个真实的Web服务,监听一个随机端口
- DEFINED_PORT,启动一个真实的Web服务,监听一个定义好的端口(从spring配置文件中获取)
- NONE,启动一个非Web的ApplicationContext,既不提供Mock环境,也不提供真实的Web服务
如果当前服务的classpath中没有包含web相关的依赖,spring将启动一个非web的ApplicationContext,此时的webEnvironment就没有什么意义了
参考
SpringBoot Test及注解详解
spring-boot-features-testing
Spring Boot中编写单元测试
网友评论