Springboot 单元测试 @SpringBootTest 与 RunWith
SpringBoot Test 是什么
Spring Test 与 JUnit 等其他测试框架结合起来,提供了便捷高效的测试方式。而 Spring Boot Test 是在Spring Test之上的再次封装,增加了切片测试,增强了 mock (模拟) 能力。
常用三类测试方式: 单元测试 @Test、切片测试 @RunWith @WebMvcTest、功能测试 @RunWith @SpringBootTest
使用
-
依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>${spring.boot.version}</version> <scope>test</scope> </dependency>
-
测试类
// @RunWith(SpringRunner.class) // junit4 使用, 非 junit4 不需要加上 @SpringBootTest public class UserServiceTest { @Autowired private UserService userService; @org.junit.jupiter.api.Test public void userInfo() { System.err.println(">>>>>>>>>>>>>>>>>>>>>>>> " + userService.info()); } }
引入 spring-boot-strater-test 后 Junit4 和 Junit5 同时存在, 两者在使用时有所不同
- @RunWith 是 Junit4 提供的注解,将 Spring 和 Junit 链接了起来。如果你习惯使用 Junit4 的 @org.junit.Test 注解, 则需要加上 @RunWith(SpringRunner.class)
- 如果没有其他特别的需求, 默认使用 Junit5 的注解 @org.junit.jupiter.api.Test 就行了, 一定注意别引错了. (使用Junit5,不再需要使用@ExtendWith 注解,@SpringBootTest 和其 @Test 默认已包含)
- 使用 @SpringBootTest 后,Spring 将加载所有被管理的 bean,基本等同于启动了整个服务,此时便可以开始功能测试
- Junit5 相比 4 有所不同: @BeforeEach is Junit4’s @Before @BeforeAll is Junit4’s @BeforeClass , only static method use @AfterEach and @AfterAll Similarly @AfterAll 包含一些清理方法, 比如资源的close; @AfterEach 包含一些 sql 语句的回滚
与 Sping Test 的不同
-
Spring:
@ContextConfiguration(locations="classpath:applicationContext.xml") // 用来指定Spring的配置文件 @RunWith(SpringJUnit4ClassRunner.class) // 指定用那种驱动进行单元测试 public class IocTest { }
- @RunWith(xx.class) 指定 Spring 的单元测试模块来执行标了@Test注解的测试方法
-
SpingBoot:
@RunWith(SpringRunner.class) @SpringBootTest public class IocTest { }
- @SpringBootTest 替代了 Sring Test 中的 @ContextConfiguration 注解, 目的是加载 ApplicationContext,启动 Spring 容器。
-
注意
- 使用 @SpringBootTest 时不用像 @ContextConfiguration 一样指定 locations 或 classes 属性,这是因为在 @SpringBootTest 注解上, 会自动检索程序的配置文件, 检索顺序是从当前包开始,逐级向上查找被 @SpringBootApplication 或 @SpringBootConfiguration 注解的类, 所以要求我们必须在 test/ 文件下有相同的包路径.
解决 Error creating bean with name ‘serverEndpointExporter’
如果在 SpringBoot 项目中, 集成了 WebSocket 并且能正常运行, 而在进行单元测试时, 报错:
javax.websocket.server.ServerContainer not available
可能存在的原因是 Websocket 是需要依赖 tomcat 等容器的启动, 而测试环境并没有真正的启动一个 tomcat 容器, 所以 Websocket 就报错了. 解决办法是在 @SpringBootTest 里添加属性 webEnvironment = RANDOM_PORT.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
上一篇:
5款热门的远程控制软件,让你事半功倍
下一篇:
它们原来都属于软件测试!