当前位置: 首页 > news >正文

SpringBoot3集成Junit5

目录

      • 1. 确保项目中包含相关依赖
      • 2. 配置JUnit 5
      • 3. 编写测试类
      • 4、Junit5 新增特性
        • 4.1 注解
        • 4.2 断言
        • 4.3 嵌套测试
        • 4.4
      • 总结

在Spring Boot 3中集成JUnit 5的步骤相对简单。以下是你可以按照的步骤:

1. 确保项目中包含相关依赖

首先,确保你的pom.xml文件中包含了Spring Boot 3和JUnit 5相关的依赖。下面是需要的基本依赖:

<dependencies><!-- Spring Boot Starter Test(包含JUnit 5支持) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- JUnit 5的依赖(Spring Boot 3已经集成JUnit 5) <dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.8.2</version><scope>test</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>5.8.2</version><scope>test</scope></dependency> -->
</dependencies>

注意spring-boot-starter-test 默认包含JUnit 5支持,所以你不需要显式地引入JUnit 5的依赖,除非你有特定版本的需求。

2. 配置JUnit 5

Spring Boot 3默认启用了JUnit 5,你只需要按照JUnit 5的方式编写测试代码即可。Spring Boot的@SpringBootTest注解会与JUnit 5兼容。

3. 编写测试类

创建一个简单的JUnit 5测试类,使用@SpringBootTest来加载Spring Boot应用程序上下文。

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class MyApplicationTests {@Testvoid test() {// 这里写测试方法}
}

4、Junit5 新增特性

4.1 注解

JUnit5的注解与JUnit4的注解有所变化
https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations
● @Test :表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一不能声明任何属性,拓展的测试将会由Jupiter提供额外测试
● @ParameterizedTest :表示方法是参数化测试,下方会有详细介绍
● @RepeatedTest :表示方法可重复执行,下方会有详细介绍
● @DisplayName :为测试类或者测试方法设置展示名称
● @BeforeEach :表示在每个单元测试之前执行
● @AfterEach :表示在每个单元测试之后执行
● @BeforeAll :表示在所有单元测试之前执行
● @AfterAll :表示在所有单元测试之后执行
● @Tag :表示单元测试类别,类似于JUnit4中的@Categories
● @Disabled :表示测试类或测试方法不执行,类似于JUnit4中的@Ignore
● @Timeout :表示测试方法运行如果超过了指定时间将会返回错误
● @ExtendWith :为测试类或测试方法提供扩展类引用

import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;class StandardTests {@BeforeAllstatic void initAll() {}@BeforeEachvoid init() {}@DisplayName("😱")@Testvoid succeedingTest() {}@Testvoid failingTest() {fail("a failing test");}@Test@Disabled("for demonstration purposes")void skippedTest() {// not executed}@Testvoid abortedTest() {assumeTrue("abc".contains("Z"));fail("test should have been aborted");}@AfterEachvoid tearDown() {}@AfterAllstatic void tearDownAll() {}}
4.2 断言

在这里插入图片描述

4.3 嵌套测试

JUnit 5 可以通过 Java 中的内部类和@Nested 注解实现嵌套测试,从而可以更好的把相关的测试方法组织在一起。在内部类中可以使用@BeforeEach 和@AfterEach 注解,而且嵌套的层次没有限制。

@DisplayName("A stack")
class TestingAStackDemo {Stack<Object> stack;@Test@DisplayName("is instantiated with new Stack()")void isInstantiatedWithNew() {new Stack<>();}@Nested@DisplayName("when new")class WhenNew {@BeforeEachvoid createNewStack() {stack = new Stack<>();}@Test@DisplayName("is empty")void isEmpty() {assertTrue(stack.isEmpty());}@Test@DisplayName("throws EmptyStackException when popped")void throwsExceptionWhenPopped() {assertThrows(EmptyStackException.class, stack::pop);}@Test@DisplayName("throws EmptyStackException when peeked")void throwsExceptionWhenPeeked() {assertThrows(EmptyStackException.class, stack::peek);}@Nested@DisplayName("after pushing an element")class AfterPushing {String anElement = "an element";@BeforeEachvoid pushAnElement() {stack.push(anElement);}@Test@DisplayName("it is no longer empty")void isNotEmpty() {assertFalse(stack.isEmpty());}@Test@DisplayName("returns the element when popped and is empty")void returnElementWhenPopped() {assertEquals(anElement, stack.pop());assertTrue(stack.isEmpty());}@Test@DisplayName("returns the element when peeked but remains not empty")void returnElementWhenPeeked() {assertEquals(anElement, stack.peek());assertFalse(stack.isEmpty());}}}
}
4.4

参数化测试是JUnit5很重要的一个新特性,它使得用不同的参数多次运行测试成为了可能,也为我们的单元测试带来许多便利。

利用@ValueSource等注解,指定入参,我们将可以使用不同的参数进行多次单元测试,而不需要每新增一个参数就新增一个单元测试,省去了很多冗余代码。

@ValueSource: 为参数化测试指定入参来源,支持八大基础类以及String类型,Class类型
@NullSource: 表示为参数化测试提供一个null的入参
@EnumSource: 表示为参数化测试提供一个枚举入参
@CsvFileSource:表示读取指定CSV文件内容作为参数化测试入参
@MethodSource:表示读取指定方法的返回值作为参数化测试入参(注意方法返回需要是一个流)

@ParameterizedTest
@ValueSource(strings = {"one", "two", "three"})
@DisplayName("参数化测试1")
public void parameterizedTest1(String string) {System.out.println(string);Assertions.assertTrue(StringUtils.isNotBlank(string));
}@ParameterizedTest
@MethodSource("method")    //指定方法名
@DisplayName("方法来源参数")
public void testWithExplicitLocalMethodSource(String name) {System.out.println(name);Assertions.assertNotNull(name);
}static Stream<String> method() {return Stream.of("apple", "banana");
}

总结

  • Spring Boot 3已经内建了对JUnit 5的支持,只要使用spring-boot-starter-test依赖即可。
  • 编写JUnit 5测试时,使用@SpringBootTest加载应用上下文。
  • 可以利用JUnit 5的生命周期方法、参数化测试等特性进行更精细的测试。
http://www.lryc.cn/news/478307.html

相关文章:

  • 【EMNLP2024】阿里云人工智能平台 PAI 多篇论文入选 EMNLP2024
  • Spark的Shuffle过程
  • Java+Swing可视化图像处理软件
  • RDD转换算子:【mapValues、mapPartitions】
  • 数组和指针的复杂关系
  • Linux系统I/O调优实例
  • 记录Ubuntu OS的异常
  • Vue 3 单元测试与E2E测试
  • 猫用空气净化器哪个牌子好?求除毛好、噪音小的宠物空气净化器!
  • 第十九课 Vue组件中的方法
  • 【JavaScript】V8,Nodejs 与浏览器
  • 内存马浅析
  • 聊一聊Elasticsearch的基本原理与形成机制
  • 应急救援无人车:用科技守护安全!
  • 详解Java之Spring MVC篇二
  • flutter鸿蒙next 使用 InheritedWidget 实现跨 Widget 传递状态
  • 计算机的错误计算(一百四十六)
  • 国标GB28181视频平台EasyCVR私有化视频平台工地防盗视频监控系统方案
  • CUDA系统学习之一软件堆栈架构
  • SpringBoot项目中替换指定版本的tomcat
  • 【5.10】指针算法-快慢指针将有序链表转二叉搜索树
  • 机器学习—前向传播的一般实现
  • 极狐GitLab 签约足下科技,加速国产智驾操作系统的发展与普及
  • 20241102在荣品PRO-RK3566开发板的预置Android13下适配宸芯的数传模块CX6603N
  • 力扣(leetcode)题目总结——哈希表篇
  • AWS RDS Oracle hit ORA-39405
  • Dinky中配置Flink集群
  • 通讯录(C 语言)
  • 对比Java和TypeScript中的服务注册和查找机制
  • Flutter 主流常用第三方库、插件收集