pom.xml
<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:Spring的测试支持。
- AssertJ:提供了流式的断言方式。
- Hamcrest:提供了丰富的matcher。
- Mockito:mock框架,可以按类型创建mock对象,可以根据方法参数指定特定的响应,也支持对于mock调用过程的断言。
- JSONassert:为JSON提供了断言功能。
- JsonPath:为JSON提供了XPATH功能。
-
package com.hs.test; import com.hs.entity.User; import com.hs.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootApplicationTests { @Autowired private UserService userService; @Test public void testAddUser() { com.hs.entity.User user = new User(); user.setName("john"); userService.insertSelective(user); } }
- @RunWith(SpringRunner.class)是JUnit的注解,作用是关联Spring Boot Test,使运行JUnit时同时启动Spring
- @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) 作用是启动Spring的ApplicationContext,参数webEnvironment指定了运行的web环境
- @AutoConfigureTestDatabase 作用是启动一个内存数据库,不使用真实的数据库
- 参考
- SpringBoot Test及注解详解 - codedot - 博客园一、Spring Boot Test介绍 Spring Test与JUnit等其他测试框架结合起来,提供了便捷高效的测试手段。而Spring Boot Test 是在Spring Test之上的再次封https://www.cnblogs.com/myitnews/p/12330297.html