后端——框架——测试框架——junit——环境 & 模块
本篇由三部分内容组成。
第一, 模块介绍。
第二, 搭建环境。引入junit相关的jar包即可。
第三, 演示示例。编写HelloWorld测试案例并运行。
1. 模块
Junit包含三个核心模块。Junit platform, Junit Jupiter, junit vintage。
1.1 platform
引用原著:
platform:the junit platform serves as a foundation for launching testing frameworks on the JVM. It also defines the Test Engine API for developing a testing framework that runs on the platform. Furthermore, the platform provides a console launcher to launch the platform from the command line and a Junit 4 based Runner for running any Test Engine on the platform in a Junit 4 based environment. First-class support for the Junit platform also exists in popular IDEs and builds tools.
平台是运行测试案例的核心包,平台的功能主要分为三个部分:
第一,提供了运行基础。测试案例的运行方式有四种,命令行,IDE,Maven插件(或其他编译打包工具的插件),程序。但是其他方式都是建立在程序基础上的。
第二,提供了TestEngine API,允许第三方实现自己的框架。类似于JDBC API,第三方提供实现。略。
第三,为实现低版本兼容性提供的相关API。略。
它的结构图如下:
launcher:运行基础。
- core:核心,在以程序方式运行测试案例时,大部分类来源于此包。
- listener:监听器。
engine:提供了Test engine的API。
suite:条件类和注解。类似于condition包。
reporting:生成报告。略。
testkit:工具箱,提供额外的功能,例如统计。
commons:存放公共类。
其他如jfr(java飞行器),console(命令行)等略。
1.2 Jupiter
引用原著:
Jupiter: Jupiter is the combination of the new programming model and extension model for writing tests and extensions in Junit 5。The Jupiter sub-project provides a Test Engine for running Jupiter based tests on the platform
Jupiter是编写测试案例的核心包。它的结构图如下:
api:核心,提供了大量的注解。编写测试案例用的大部分类都来源于此包。
- condition:条件相关的注解和API,类似ExectutionCondition。@Disabled等。
- extension:提供大部分的扩展功能。
- function:涉及到的函数接口。
- io:io相关,只有一个注解@TempDir。
- parallel:多线程相关。
params:核心,测试案例方法参数相关的所有内容都来源于此包。
- converter:类型转换器,
- provider:类型提供者,类似于Supplier函数接口。
- aggregator:
engine:实现平台提供的Test Engine相关API。
migrationsupport:低版本兼容性。
1.3 vintage
引用原著:
vintage: vintage provides a Test Engine for running Junit 3 and Junit 4 based tests on the platform. It requires Junit 4.12 or later to be present on the class/module path
是为了向低版本兼容。略。
2. 环境搭建
搭建环境的步骤如下:
第一步,添加maven依赖。若是spring boot,添加spring-boot-test依赖。
org.junit junit-bom 5.8.1 pom import org.junit.jupiter junit-jupiter test org.junit.platform junit-platform-launcher test org.junit.platform junit-platform-engine test
第二步,编写测试案例。
第三步,运行测试案例。 mvn test
3. HelloWorld示例
public class TestHelloWorld{ // log object private static Logger log = LoggerFactory.getLogger(TestHelloWorld.class); @Test public void test() { IntStream ints = IntStream.range(1, 380); // 1-300之间的偶数,用逗号拼接 String strs = ints.filter((x) -> x % 2 == 0).mapToObj(String::valueOf).collect(Collectors.joining(",")); log.info("结果:{}", strs); } }
代码非常简单,打印1-300之间的偶数。运行即可。