Springboot中测试问题(@SpringbootTest)

1、简介

        在日常开发中,我们经常需要对我们的代码进行输入输出进行测试,为了便捷测试,Springboot提供测试注解,帮助我们更加便捷实现测试。

2、Springboot测试中使用到的注解
2.1、@SpringBootTest注解使用

        @SpringBootTest 替代了 Spring Test 中的 @ContextConfiguration 注解,目的是加载 ApplicationContext,启动 Spring 容器。在测试类中使用,需要注意以下两点:

1)、在使用 @SpringBootTest 时不用像 @ContextConfiguration 一样指定 locations 或 classes 属性,这是因为在 @SpringBootTest 注解上, 会自动检索程序的配置文件, 检索顺序是从当前包开始,逐级向上查找被 @SpringBootApplication 或 @SpringBootConfiguration 注解的类, 所以要求我们必须在测试文件目录(test/)下和这两个注解有相同的包路径。否则需要指定对应的类。

@SpringBootTest(classes = {TestMain.class})

2)、在 SpringBoot 项目中, 集成了 WebSocket,由于Websocket 是需要依赖 tomcat 等容器的启动, 而测试环境并没有真正的启动一个 tomcat 容器,启动会报错,解决办法是在 @SpringBootTest 里添加属性 webEnvironment = RANDOM_PORT。

@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
2.2、@RunWith注解

        @RunWith(xx.class) 指定 Spring 的单元测试模块来执行标注了 @Test 注解的测试方法。

2.3、@Test 注解使用

        @Test注解有两个版本,Junit4 和 Junit5引入 spring-boot-strater-test  后 Junit4 和 Junit5 同时存在,两者在使用时有所不同,引入的包分别如下:

// Junit4
import org.junit.Test
// Junit5
import org.junit.jupiter.api.Test

注:Junit4 的 注解, 则需要加上 @RunWith(SpringRunner.class)一起使用,如果不加@RunWith注解,Spring容器不会启动。

2.3.1、Junit4

      对于Junit4,通常使用如下注解 :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestClass{
    @Test
    public void test(){}
}
  2.3.2、Junit5

        对于Junit5,通常使用如下注解:

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class TestClass{
    @Test
    public void test(){}
}
3、总结

        本文介绍关于Springboot中测试使用方法以及遇到问题解决方式,关于如何进行MOCK接口进行测试将在后续进行详解。

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知其_所以然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值