Junit5基础教程

Junit5的构成:

  • Junit Platform+Junit Jupiter+Junit Vintage
  • Junit Platform:是Junit向测试平台演进,提供平台功能的模块,通过这个其他的自动化引擎可以接入Junit,实现对接和执行
  • Junit Jupiter:核心,承载Juint4原有功能+丰富的新特性
  • Junit Vintage:主要功能是对Juint旧版本进行兼容

一,导入依赖

 <properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><junit-platform.version>1.8.1</junit-platform.version><junit-jupiter.version>5.8.1</junit-jupiter.version></properties><build><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>3.0.0-M5</version><dependencies><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>5.8.1</version></dependency></dependencies><configuration><includes><include>**/*Test.java</include></includes></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></pluginManagement></build><!--核心依赖--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>5.8.1</version></dependency><!--套件测试使用--><dependency><groupId>org.junit.platform</groupId><artifactId>junit-platform-runner</artifactId><version>1.8.1</version></dependency><dependency><groupId>org.junit.platform</groupId><artifactId>junit-platform-runner</artifactId><version>1.8.1</version></dependency>

二,基本功能

一、常用断言

在这里插入图片描述

二、执行顺序和常用注解

1、通过BeforeAll类的注解来保证顺序
// 执行顺序:beforeAll-beforeEach-afterEach-afterAll
@DisplayName("常用注解测试")
public class TestCase {/*** @BeforeAll和@AfterAll 必须静态修饰,在所有方法执行前后只执行一次* @Test 一个方法* @AfterEach和@BeforeEach 每次方法执行前都会执行一次* @DisplayName() 类似注解的功能* @RepeatedTest(5) 重复5次* @Disabled 不执行该方法* @Tags 打标签*/@BeforeAllpublic static void beforeAll() {System.out.println("BeforeAll再每个类中只执行一次,且是在开头执行");}@BeforeEachpublic void beforeEach() {System.out.println("BeforeEach在每个方法执行前都会执行一次");}// junit5不需要访问修饰符//  @Disabled表示不执行@Test@Disabled@DisplayName("方法1")void fun1() {System.out.println("---fun1---");}@Test@DisplayName("方法2")@RepeatedTest(5)void fun2() {System.out.println("---fun2---");}@Test@Tag("tag1")void tagTest(){System.out.println("tag1");}@AfterEachpublic void afterEach() {System.out.println("AfterEach在每个方法执行前都会执行一次");}@AfterAllpublic static void afterAll() {System.out.println("afterAll再每个类中只执行一次,且是在结尾执行");}
}
2、通过order注解来保证执行顺序
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;@TestMethodOrder(OrderAnnotation.class)
class OrderedTestsDemo {@Test@Order(1)void nullValues() {// perform assertions against null values}@Test@Order(2)void emptyValues() {// perform assertions against empty values}@Test@Order(3)void validValues() {// perform assertions against valid values}
}
  • allure注解
    在这里插入图片描述

三、依赖测试

/*** @Nested:* 功能类似于suite测试套件* 从下往上执行*/public class NestedTest {private static HashMap<String, Object> dataMap = new HashMap<String, Object>();@Testvoid login() {dataMap.put("login", "登录成功");}@Nestedclass Shopping{@Testvoid shopping(){if (null!=dataMap.get("buy")){System.out.println("购买成功啦!");}else {System.out.println("购买失败");}}}@Nestedclass Buy {@Testvoid buyTest() {if (dataMap.get("login").equals("登录成功")) {System.out.println("登录成功");dataMap.put("buy", "登录成功,快去购物吧!");} else {System.out.println("登录失败");}}}
}

四、参数化测试

写过一篇,点这里!!

五、测试套件

SelectPackages、IncludePackages、SelectClasses、IncludeTags等注解的使用
/*** SelectPackages 选择需要执行的包*/
@RunWith(JUnitPlatform.class)
@SelectPackages({"com.testCase2"})
public class SelectPackagesTest {}
/*** @IncludePackages需要和@SelectPackages搭配使用* @IncludePackages是在@SelectPackages的基础上再做一层筛选* ps:一定要注意,包下的类名一定要Test开头或者结尾,否则就不执行了!!!*/
@RunWith(JUnitPlatform.class)
@SelectPackages({"com.testCase2"})
// 只执行com.testCase2.demo1
@IncludePackages({"com.testCase2.demo1"})
public class IncludePackagesTest {
}
/*** @SelectClasses和@IncludeTags组合使用,在方法里选出对应的标签* 还有@ExcludeTag*/
@RunWith(JUnitPlatform.class)
@SelectClasses({TestCase.class})
//@IncludeTags("tag1")
@ExcludeTags("tag1")
public class SelectClassesTest {
}

六、软断言

  • assertAll断言方法,会在执行完所有断言后统⼀输出结果,⼀次性暴露所有问题,提高了测试脚本的健壮性。
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;import java.util.ArrayList;
import java.util.List;import static org.junit.jupiter.api.Assertions.assertAll;public class AssertAllDemo {// 普通方法,第一个执行失败以后后面都不执行@Testvoid assertTest1() {Assertions.assertTrue(2 == 1);}void assertTest2() {Assertions.assertTrue(3 == 1);}void assertTest3() {Assertions.assertTrue(1 == 1);}// 用了assertAll之后,所有方法都执行@Testvoid assertAllTest() {assertAll("多次结果校验",() -> {Assertions.assertTrue(2 == 1);},() -> {Assertions.assertTrue(3 == 1);});}@Testvoid assertAllTtest02() {List<Executable> assertList = new ArrayList<>();for (int i = 0; i < 10; i++) {int result = i;System.out.println(result);assertList.add(() -> {Assertions.assertEquals(10, result);});}assertAll("多次结果校验", assertList.stream());}}

七、并发测试

  • 测试环境基本上都是单线程操作,而线上存在分布式的并发场景,所以并不能暴露所有问题,这里就需要用到并发
  • junit测试是在⼀个线程中串行执行的,从5.3开始⽀持并行测试。⾸先需要在配置⽂件junit-platform.properties 中配置。
#是否允许并行执行true/false
junit.jupiter.execution.parallel.enabled = true
#是否支持方法级别多线程same_thread/concurrent
junit.jupiter.execution.parallel.mode.default = concurrent
#是否支持类级别多线程same_thread/concurrent
junit.jupiter.execution.parallel.mode.classes.default = concurrent
# the maximum pool size can be configured using a ParallelExecutionConfigurationStrategy
junit.jupiter.execution.parallel.config.strategy=fixed
junit.jupiter.execution.parallel.config.fixed.parallelism=4

import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;/*** 并发测试*/
public class ParallelTest {static   int result = 0;// 加synchronized可以保证其原子性,但是如果是分布式系统是不适合的,需要用如redis分布式锁public static  int cal(int x) throws InterruptedException {int i = result;Thread.sleep(1000);result = i + x;return result;}public static int add(int x,int y) throws InterruptedException {Thread.sleep(1000);result = y + x;return result;}@RepeatedTest(10)public void testCal() throws InterruptedException {long id = Thread.currentThread().getId();System.out.println("线程" + id + "为你服务:" + cal(1));}@RepeatedTest(10)public void testAdd() throws InterruptedException {long id = Thread.currentThread().getId();System.out.println("加法计算:线程" + id + "为你服务:" + add(1,2));}
}

八、动态测试解决硬编码问题

  • 传统自动化测试思路中,我们的测试逻辑是在以硬编码的形式组织到代码里的,当遇到用例迁移或结果整合时,会产生大量的逻辑重写
  • JUnit5提供了动态测试方案,让测试人员可以在脚本Runtime时动态的批量生成用例
  • 现在我们有一个需求,要把yaml文件内容转为测试用例,解决思路如下:
    在这里插入图片描述
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;/*** 动态测试demo* 需求:把result.yaml脚本变成测试用例* 首先把它通过反序列化变成对象* 然后把它添加到dynamicTestList*/
public class ShellTestResult {@TestFactoryCollection<DynamicTest> shellTestResult() throws IOException {// 新建一个列表来存储数据(不是结果)List<DynamicTest> dynamicTestList = new ArrayList<>();ObjectMapper mapper = new ObjectMapper(new YAMLFactory());// 反序列化方式把yaml文件转换为对象列表ResultList resultList = mapper.readValue(new File("D:\\interface_auto\\src\\main\\resources\\result.yaml"), ResultList.class);System.out.println("done");// 动态遍历生成测试方法for (Result result : resultList.getResultList()) {// 把数据收集起来dynamicTestList.add(// 动态生成测试方法DynamicTest.dynamicTest(result.getCaseName(), () -> {Assertions.assertTrue(result.isResult());}));}return dynamicTestList;}
}
import lombok.Data;@Data
public class Result {private String caseName;private boolean result;public boolean isResult() {return result;}public void setResult(boolean result) {this.result = result;}
}
@Data
public class ResultList {private List<Result> resultList;
}

九、Junit5启动类(适用于持续集成)

import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;import static org.junit.platform.engine.discovery.ClassNameFilter.includeClassNamePatterns;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;/*** junit5启动类(适用于持续集成这种点不了执行的)*/
public class LauncherDemo {public static void main(String[] args) {LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request().selectors(// 2个过滤条件是or不是and:selectPackage("com.learn.junit5"),selectClass(TestExecutionOrder.class)).filters(
//                includeClassNamePatterns("Test.*")).build();Launcher launcher = LauncherFactory.create();TestExecutionListener listener = new SummaryGeneratingListener();launcher.registerTestExecutionListeners(listener);launcher.execute(request);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/679643.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Spark MLlib

目录 一、Spark MLlib简介 &#xff08;一&#xff09;什么是机器学习 &#xff08;二&#xff09;基于大数据的机器学习 &#xff08;三&#xff09;Spark机器学习库MLlib 二、机器学习流水线 &#xff08;一&#xff09;机器学习流水线概念 &#xff08;二&#xff09…

Vue核心基础2:事件处理 和 事件修饰符

1 事件处理 1.1 点击事件 <body><div id"root"><h1>姓名&#xff1a; {{ name }}</h1><h1>地址&#xff1a; {{ address }}</h1><!-- <button v-on:click"showInfo">提示信息</button> --><!-…

Spring中常见的设计模式

使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性、程序的重用性、更具有灵活、优雅&#xff0c;而Spring中共有九种常见的设计模式 工厂模式 工厂模式&#xff08;Factory Pattern&#xff09;是 Java 中最常用的设计模式之一。这种类型的设计模式属于…

Linux命令-blkid命令(查看块设备的文件系统类型、LABEL、UUID等信息)

说明 在Linux下可以使用 blkid命令 对查询设备上所采用文件系统类型进行查询。blkid主要用来对系统的块设备&#xff08;包括交换分区&#xff09;所使用的文件系统类型、LABEL、UUID等信息进行查询。要使用这个命令必须安装e2fsprogs软件包。 语法 blkid -L | -U blkid [-c…

C __attribute__编译属性整理

背景 最近在看VPP源码&#xff0c;很多变量、函数都设置了编译属性&#xff0c;编译属性的作用却不是很明确&#xff0c;为了增加记忆以及方便日后查阅&#xff0c;在此整理并分享给大家。 概念 __attribute__是GCC的一大特色&#xff0c;attribute机制可以用于设置函数属性&a…

C语言数据结构:数组 vs 链表的性能评估与适用场景

本文将介绍C语言中的数据结构数组和链表&#xff0c;并对它们的性能进行评估&#xff0c;并提供适用场景的建议。 首先&#xff0c;让我们深入了解数组和链表的本质和特点。 数组是一种线性数据结构&#xff0c;它由一组相同类型的元素组成&#xff0c;这些元素在内存中连续存…

第5集《佛说四十二章经》

和尚尼慈悲、诸位法师、诸位居士&#xff0c;阿弥陀佛&#xff01; 请大家打开讲义第五面&#xff0c;第三章、割爱去贪。 蕅益大师他把《四十二章经》的内涵分成两个部分&#xff1a;第一部分是第一章、第二章的正道法门&#xff1b;其次&#xff0c;第三章之后共有四十章都…

Java图形化界面编程—— ImageIO 笔记

2.8.4 ImageIO的使用 在实际生活中&#xff0c;很多软件都支持打开本地磁盘已经存在的图片&#xff0c;然后进行编辑&#xff0c;编辑完毕后&#xff0c;再重新保存到本地磁盘。如果使用AWT要完成这样的功能&#xff0c;那么需要使用到ImageIO这个类&#xff0c;可以操作本地磁…

【MATLAB】GA_BP神经网络回归预测算法

有意向获取代码&#xff0c;请转文末观看代码获取方式~也可转原文链接获取~ 1 基本定义 GA_BP神经网络回归预测算法结合了遗传算法&#xff08;Genetic Algorithm, GA&#xff09;和BP神经网络&#xff08;Backpropagation Neural Network, BPNN&#xff09;&#xff0c;用于解…

分享88个文字特效,总有一款适合您

分享88个文字特效&#xff0c;总有一款适合您 88个文字特效下载链接&#xff1a;https://pan.baidu.com/s/1Y0JCf4vLyxIJR6lfT9VHvg?pwd8888 提取码&#xff1a;8888 Python采集代码下载链接&#xff1a;采集代码.zip - 蓝奏云 学习知识费力气&#xff0c;收集整理更不…

【PTA|选择题|期末复习】字符串(二)

【PTA|期末复习|选择题】字符串&#xff08;一&#xff09; 2-23 设有数组定义“char array[ ] "China", 则数组array所占的空间为()。 A.4个字节 B.5个字节 C.6个字节 D.7个字节 2-24 有定义“char x[ ] " abcdefg "; char y [ ]{a, b, c, d, e , f, …

Gemini VS GPT-4,当前两大顶级AI模型实测

随着谷歌在AI军备竞赛中急起直追&#xff0c;“有史以来最强大模型”Gemini Advanced终于上线&#xff0c;AI爱好者们总算等来了一款号称能够匹敌GPT-4的大语言模型。 月费19.99美元&#xff08;包含Google One订阅&#xff09;的Gemini Advanced实际表现如何&#xff1f;究竟…

spring boot 通过 application 切换cache使用的服务

上文 spring boot整合 cache 以redis服务 处理数据缓存 便捷开发 我们写了个整合缓存的基本功能 但 其实我也因为很多时候redis服务没起 等等原因 导致缓存功能整个用不了 其实 最简单的就是 将redis相关配置去掉 不过为了方便 我们可以这样 application.yml文件中这样写 spr…

C++进阶(十五)C++的类型转换

&#x1f4d8;北尘_&#xff1a;个人主页 &#x1f30e;个人专栏:《Linux操作系统》《经典算法试题 》《C》 《数据结构与算法》 ☀️走在路上&#xff0c;不忘来时的初心 文章目录 一、C语言中的类型转换二、为什么C需要四种类型转换三、C强制类型转换1、static_cast2、reint…

常见的开源机器人操作系统介绍

开源机器人操作系统&#xff08;Open Source Robot Operating Systems&#xff0c;ROS&#xff09;为机器人开发提供了强大的工具和库&#xff0c;使得机器人设计和实现更加高效和便捷。以下是一些常见的开源机器人操作系统&#xff1a; 1. ROS&#xff08;Robot Opera…

[office] excel如何计算毛重和皮重的时间间隔 excel计算毛重和皮重时间间隔方法 #笔记#学习方法

excel如何计算毛重和皮重的时间间隔 excel计算毛重和皮重时间间隔方法 在日常工作中经常会到用excel&#xff0c;有时需要计算毛重和皮重的时间间隔&#xff0c;具体的计算方式是什么&#xff0c;一起来了解一下吧 在日常工作中经常会到用excel&#xff0c;在整理编辑过磅数据…

Github 2024-02-10 开源项目日报Top10

根据Github Trendings的统计&#xff0c;今日(2024-02-10统计)共有10个项目上榜。根据开发语言中项目的数量&#xff0c;汇总情况如下&#xff1a; 开发语言项目数量Python项目5Solidity项目1Go项目1Rust项目1PLpgSQL项目1Scala项目1TypeScript项目1 Bluesky Social 应用程序…

Linux--基础开发工具篇(2)(vim)(配置白名单sudo)

目录 前言 1. vim 1.1vim的基本概念 1.2vim的基本操作 1.3vim命令模式命令集 1.4vim底行命令 1.5 异常问题 1.6 批量注释和批量去注释 1.7解决普通用户无法sudo的问题 1.8简单vim配置 前言 在前面我们学习了yum&#xff0c;也就是Linux系统的应用商店 Linux--基础开…

Object类详解

所有类都是Object类的子类&#xff0c;也都具备Object类的所有特性。 Object类的基本特性&#xff1a; 1.Object类是所有类的父类&#xff0c;所有的Java对象都拥有Object类的属性和方法。 2.如果在类的声明中未使用extends&#xff0c;则默认继承Object类。 public class Pe…

2024牛客寒假算法基础集训营2-c Tokitsukaze and Min-Max XOR

来源 题目 Tokitsukaze 有一个长度为 n 的序列 a1,a2,…,an和一个整数 k。 她想知道有多少种序列 b1,b2,…,bm满足&#xff1a; 其中 ⊕\oplus⊕ 为按位异或&#xff0c;具体参见 百度百科&#xff1a;异或 答案可能很大&#xff0c;请输出  mod1e97 后的结果。 输入描述…