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 同时存在, 两者在使用时有所不同

  1. @RunWith 是 Junit4 提供的注解,将 Spring 和 Junit 链接了起来。如果你习惯使用 Junit4 的 @org.junit.Test 注解, 则需要加上 @RunWith(SpringRunner.class)

  2. 如果没有其他特别的需求, 默认使用 Junit5 的注解 @org.junit.jupiter.api.Test 就行了, 一定注意别引错了. (使用Junit5,不再需要使用@ExtendWith 注解,@SpringBootTest 和其 @Test 默认已包含)

  3. 使用 @SpringBootTest 后,Spring 将加载所有被管理的 bean,基本等同于启动了整个服务,此时便可以开始功能测试

  4. Junit5 相比 4 有所不同:

    1. @BeforeEach is Junit4’s @Before
    2. @BeforeAll is Junit4’s @BeforeClass , only static method use
    3. @AfterEach and @AfterAll Similarly
    4. @AfterAll 包含一些清理方法, 比如资源的close; @AfterEach 包含一些 sql 语句的回滚

在这里插入图片描述

与 Sping Test 的不同

  • Spring:
@ContextConfiguration(locations="classpath:applicationContext.xml") // 用来指定Spring的配置文件
@RunWith(SpringJUnit4ClassRunner.class) // 指定用那种驱动进行单元测试
public class IocTest {
}
  1. @RunWith(xx.class) 指定 Spring 的单元测试模块来执行标了@Test注解的测试方法
  • SpingBoot:
@RunWith(SpringRunner.class)
@SpringBootTest
public class IocTest {
}
  1. @SpringBootTest 替代了 Sring Test 中的 @ContextConfiguration 注解,
    目的是加载 ApplicationContext,启动 Spring 容器。
  • 注意
  1. 使用 @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)
  • 13
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值