Spring Test与JUnit结合起来提供了高效便捷的测试解决方案,而Spring Boot Test是在Spring Test之上增加了切片测试并增强了Mock能力。
Spring Boot Test支持的测试种类,主要分为以下三类:
测试过程中的关键要素及支撑方式如下:
@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后,相关的测试依赖的类库也将一起依赖进来
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;
}
}
复制代码
使用@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;
}
}
复制代码
如果当前服务的classpath中没有包含web相关的依赖,spring将启动一个非web的ApplicationContext,此时的webEnvironment就没有什么意义了
SpringBoot Test及注解详解
spring-boot-features-testing
Spring Boot中编写单元测试