Spring 框架提供了一个专门的测试模块(spring-test),用于应用程序的集成测试。 在 Spring Boot 中,你可以通过spring-boot-starter-test启动器快速开启和使用它。
1、pom文件加入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、开启测试:
@SpringBootTest注解是SpringBoot自1.4.0版本开始引入的一个用于测试的注解。
@SpringBootTest 用来指定SpringBoot应用程序的入口类, 该注解默认会根据包名逐级往上找, 一直找到一个SpringBoot主程序class为止, 然后启动该类为单元测试准备Spring上下文环境. Spring单元测试并不在每个测试方法前都创建一个全新的Spring上下文, 因为这样做太耗费时间, 而是会缓存上下文环境. 如果某个测试方法需要重新准备Spring上下文, 需要在该方法上加 @DirtiesContext 注解.
@RunWith(SpringRunner.class)
//@SpringBootTest(classes={DemoApplication.class,...}),多个类使用大括号
@SpringBootTest(classes=DemoApplication.class)//指定启动类(SpringBootApplication注解的类)
public class TestCase {
@Autowired
private UserMapper userMapper;
@Test
public void test() {
List<User> list = userMapper.findAll();
System.out.println(list);
}
}