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接口进行测试将在后续进行详解。

相关推荐

  1. Springboot测试问题(@SpringbootTest

    2024-04-23 11:58:01       37 阅读
  2. 测试学习笔记1:@SpringbootTest测试注解详解

    2024-04-23 11:58:01       61 阅读
  3. IDEA SpringBoot + Gradle无法运行测试问题

    2024-04-23 11:58:01       40 阅读
  4. 软件测试面试的自动化问题

    2024-04-23 11:58:01       48 阅读
  5. 解决SpringBoot 测试类无法自动注入@Autowired的问题

    2024-04-23 11:58:01       55 阅读
  6. SpringBoot Gateway整合过程问题

    2024-04-23 11:58:01       78 阅读
  7. Springboot项目Controller层的单元测试

    2024-04-23 11:58:01       164 阅读
  8. 软件测试面试基础与功能的问题

    2024-04-23 11:58:01       50 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 11:58:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 11:58:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 11:58:01       87 阅读
  4. Python语言-面向对象

    2024-04-23 11:58:01       96 阅读

热门阅读

  1. spring boot破解xjar.go加密后的jar包

    2024-04-23 11:58:01       33 阅读
  2. playwright基本入门必备知识点

    2024-04-23 11:58:01       36 阅读
  3. 鸿蒙开发基础认证 课后习题汇总

    2024-04-23 11:58:01       26 阅读
  4. 3D抓取算法的优点及缺点

    2024-04-23 11:58:01       30 阅读
  5. Spring Boot统一功能处理

    2024-04-23 11:58:01       31 阅读
  6. level2行情+在线金融数据库

    2024-04-23 11:58:01       38 阅读