浅解 Junit 4 第二篇: Runner 和 ParentRunner

背景

浅解 Junit 4 第一篇:TestClass 一文中,我们探讨了 org.junit.runners.model.TestClass \text{org.junit.runners.model.TestClass} org.junit.runners.model.TestClass 的功能。在此基础上,我们继续探索 JUnit 4 里的其他核心类。本文会 初步探讨 JUnit 4 如何找到并运行带有 @Test 注解的方法。本文的主角是以下两位

  • org.junit.runner.Runner \text{org.junit.runner.Runner} org.junit.runner.Runner
  • org.junit.runners.ParentRunner \text{org.junit.runners.ParentRunner} org.junit.runners.ParentRunner

要点

对一个测试类 T \text{T} T 而言,我们记

  • T \text{T} T 对应的 org.junit.runners.model.TestClass \text{org.junit.runners.model.TestClass} org.junit.runners.model.TestClass 为 TestClass T \text{TestClass}_\text{T} TestClassT
  • T \text{T} T 对应的 org.junit.runner.Runner \text{org.junit.runner.Runner} org.junit.runner.Runner 为 Runner T \text{Runner}_\text{T} RunnerT

那么

  • Runner T \text{Runner}\text{T} RunnerT 借助 TestClass T \text{TestClass}\text{T} TestClassT 可以找到 T \text{T} T 中带有 @Test 注解的方法 m e t h o d 1 , m e t h o d 2 , ⋯ method_1,method_2,\cdots method1,method2,⋯
  • Runner T \text{Runner}_\text{T} RunnerT 负责运行 m e t h o d 1 , m e t h o d 2 , ⋯ method_1,method_2,\cdots method1,method2,⋯

正文

一个具体的场景: 用 Nand 来实现 Not/And/Or

说明:完整的代码,下文会提供。这一小节为了行文方便,只用截图和类图进行说明。

The Elements of Computing Systems 一书的附录 A 中提到了如下的结论 (只用 Nand 运算符来表示任意的布尔函数 一文中有更多细节)

任何布尔函数都可以用只包含 Nand 运算符的表达式表示

基于这一结论,我们可以只用 Nand 来实现 Not/And/Or,相关类图如下

classDiagram class NandGate{ +calc(boolean, boolean) boolean } class NotGate{ -NandGate nandGate +calc(boolean) boolean } class AndGate{ -NandGate nandGate +calc(boolean, boolean) boolean } class OrGate{ -NandGate nandGate +calc(boolean, boolean) boolean }

写好 NandGate/NotGate/AndGate/OrGate 这些类的代码后,需要对它们进行测试,对应测试类的类图如下

classDiagram class NandGateTest { - NandGate nandGate +test_true_true() void +test_true_false() void +test_false_true() void +test_false_false() void } class NotGateTest{ -NotGate notGate +test_true() void +test_false() void } class AndGateTest{ -AndGate andGate +test_true_true() void +test_true_false() void +test_false_true() void +test_false_false() void } class OrGateTest{ -OrGate orGate +test_true_true() void +test_true_false() void +test_false_true() void +test_false_false() void }

NandGateTest 为例,它有 4 个带有 @Test 注解的方法

如何找到并运行带有 @Test 注解的方法

找到带有 @Test 注解的方法

我们通过 NandGateTest 对应的 TestClass(全称是 org.junit.runners.model.TestClass \text{org.junit.runners.model.TestClass} org.junit.runners.model.TestClass) 就可以找到这 4 个带有 @Test 注解的方法。思维导图如下 👇

mindmap Root{{"NandGateTest"}} TC)"NandGateTest<br/>对应的<br/>TestClass"( f1("public void test_true_true() 方法") f2("public void test_true_false() 方法") f3("public void test_false_true() 方法") f4("public void test_false_false() 方法")

为了便于描述,我们把 NandGateTest \text{NandGateTest} NandGateTest 对应的 TestClass \text{TestClass} TestClass 称为 TestClass NandGateTest \text{TestClass}_\text{NandGateTest} TestClassNandGateTest,4 个带有 @Test 注解的方法分别称为 m e t h o d 1 , m e t h o d 2 , m e t h o d 3 , m e t h o d 4 method_1,method_2,method_3,method_4 method1,method2,method3,method4。

借助 TestClass NandGateTest \text{TestClass}_\text{NandGateTest} TestClassNandGateTest,我们可以找到 NandGateTest \text{NandGateTest} NandGateTest 中带有 @Test 注解的方法,简要的代码如下 👇 (这里就不写完整的 main 方法了)

java 复制代码
TestClass testClass = new TestClass(NandGateTest.class);
List<FrameworkMethod> annotatedMethods = testClass.getAnnotatedMethods(Test.class);

示例效果如下图所示 👇

运行带有 @Test 注解的方法

但是我们应该如何运行带有 @Test 注解的这些方法呢?

一个思路是:进行更高层的抽象。我们可以定义一个 Runner \text{Runner} Runner 类( Runner \text{Runner} Runner 可以翻译为 运行器 ,由它来运行测试,所以叫运行器)。 Runner \text{Runner} Runner 持有 TestClass \text{TestClass} TestClass, Runner \text{Runner} Runner 通过 TestClass \text{TestClass} TestClass 找到带有 @Test 注解的各个方法, Runner \text{Runner} Runner 负责运行这些方法。对 NandGateTest \text{NandGateTest} NandGateTest 而言,对应的 Runner \text{Runner} Runner 可以称为 Runner NandGateTest \text{Runner}_\text{NandGateTest} RunnerNandGateTest。这里的要点如下 👇

  • Runner NandGateTest \text{Runner}\text{NandGateTest} RunnerNandGateTest 持有 TestClass NandGateTest \text{TestClass}\text{NandGateTest} TestClassNandGateTest
  • Runner NandGateTest \text{Runner}\text{NandGateTest} RunnerNandGateTest 借助 TestClass NandGateTest \text{TestClass}\text{NandGateTest} TestClassNandGateTest 找到 NandGateTest \text{NandGateTest} NandGateTest 中所有带有 @Test 注解的方法,即
    • m e t h o d 1 method_1 method1
    • m e t h o d 2 method_2 method2
    • m e t h o d 3 method_3 method3
    • m e t h o d 4 method_4 method4
  • Runner NandGateTest \text{Runner}_\text{NandGateTest} RunnerNandGateTest 负责运行带有 @Test 注解的方法,即
    • m e t h o d 1 method_1 method1
    • m e t h o d 2 method_2 method2
    • m e t h o d 3 method_3 method3
    • m e t h o d 4 method_4 method4

我们可以将 Runner NandGateTest \text{Runner}_\text{NandGateTest} RunnerNandGateTest 看成 亲子结构

  • 亲(parent): Runner NandGateTest \text{Runner}_\text{NandGateTest} RunnerNandGateTest 自身(可以将它自身视为子节点的 容器
  • 子(child): 带有 @Test 注解的方法,即
    • m e t h o d 1 method_1 method1
    • m e t h o d 2 method_2 method2
    • m e t h o d 3 method_3 method3
    • m e t h o d 4 method_4 method4

思维导图如下(中间的蓝色节点表示 parent,其余节点是 4child

mindmap Root{{Runner for NandGateTest}} C1("子节点1:<br/>method1") C2("子节点2:<br/>method2") C3("子节点3:<br/>method3") C4("子节点4:<br/>method4")

由于需要处理"查找作为子节点的方法"这样的逻辑,所以可以将 Runner \text{Runner} Runner 设计成接口或者抽象类,让它的子类(在 JUnit 4 里,这个子类是 org.junit.runners.ParentRunner \text{org.junit.runners.ParentRunner} org.junit.runners.ParentRunner)来处理具体的逻辑。下方是一个大大简化了的类图(类图中只画了 Runner \text{Runner} Runner 和 ParentRunner \text{ParentRunner} ParentRunner 里本文关心的部分)👇

classDiagram class Runner Runner <|-- `ParentRunner~T~` <<Abstract>> Runner <<Abstract>> `ParentRunner~T~` class Runner { +run(RunNotifier) void } class `ParentRunner~T~` { +run(RunNotifier) void #getChildren()* List~T~ }

ParentRunner \text{ParentRunner} ParentRunner 的 javadoc 的内容如下,可供参考。

java 复制代码
/**
 * Provides most of the functionality specific to a Runner that implements a
 * "parent node" in the test tree, with children defined by objects of some data
 * type {@code T}. (For {@link BlockJUnit4ClassRunner}, {@code T} is
 * {@link Method} . For {@link Suite}, {@code T} is {@link Class}.) Subclasses
 * must implement finding the children of the node, describing each child, and
 * running each child. ParentRunner will filter and sort children, handle
 * {@code @BeforeClass} and {@code @AfterClass} methods,
 * handle annotated {@link ClassRule}s, create a composite
 * {@link Description}, and run children sequentially.
 *
 * @since 4.5
 */

ParentRunner \text{ParentRunner} ParentRunner 中定义了抽象方法 getChildren() 👇 通过调用这个方法可以获取子节点组成的 List

org.junit.runners.BlockJUnit4ClassRunner \text{org.junit.runners.BlockJUnit4ClassRunner} org.junit.runners.BlockJUnit4ClassRunner 是 ParentRunner \text{ParentRunner} ParentRunner 的一个子类,它的 getChildren() 方法逻辑如下

mindmap Root{{"getChildren() 方法"}} A("调用 computeTestMethods()") B("步骤1:<br/>获取对应的 TestClass") C("步骤2:<br/>通过 TestClass 的实例<br/>获取带有 @Test 注解的方法")

相关代码

我创建了一个小项目来以便于学习 JUnit 4,这个项目中包含以下目录/文件(.idea/ 目录与 target/ 目录以及 junit-study.iml 文件均略去)

  • src/main/java/org/example 目录下有以下文件
    • NandGate.java
    • NotGate.java
    • AndGate.java
    • OrGate.java
  • src/test/java/org/study 目录下有以下文件
    • NandGateTest.java
    • NotGateTest.java
    • AndGateTest.java
    • OrGateTest.java
  • pom.xml (在项目顶层)

执行以下 shell 命令,就可以生成上述目录/文件(文件内容为空,下文列出了 NandGate.java/NandGateTest.java/pom.xml 等文件的内容,需要手动复制粘贴过去)

bash 复制代码
mkdir junit-study
cd junit-study

mkdir -p src/main/java/org/example/
mkdir -p src/test/java/org/study/

touch src/main/java/org/example/NotGate.java
touch src/main/java/org/example/OrGate.java
touch src/main/java/org/example/AndGate.java
touch src/main/java/org/example/NandGate.java

touch src/test/java/org/study/NotGateTest.java
touch src/test/java/org/study/NandGateTest.java
touch src/test/java/org/study/AndGateTest.java
touch src/test/java/org/study/OrGateTest.java

touch pom.xml

pom.xml

pom.xml 文件内容如下(因为我们只关注 JUnit 4,所以只有 JUnit 4 的依赖)

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>junit-study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

src/main/java 目录下的各个文件

src/main/java 目录下有如下 4java 文件

  • src/main/java/org/example/NotGate.java
  • src/main/java/org/example/OrGate.java
  • src/main/java/org/example/AndGate.java
  • src/main/java/org/example/NandGate.java

它们的内容如下 ⬇️

src/main/java/org/example/NandGate.java ⬇️

java 复制代码
package org.example;

public class NandGate {
    public boolean calc(boolean a, boolean b) {
        return !a || !b;
    }
}

src/main/java/org/example/NotGate.java ⬇️

java 复制代码
package org.example;

public class NotGate {
    private final NandGate nandGate = new NandGate();

    /**
     * not(in) = not(in & in) = nand(in, in)
     */
    public boolean calc(boolean in) {
        return nandGate.calc(in, in);
    }
}

src/main/java/org/example/AndGate.java ⬇️

java 复制代码
package org.example;

public class AndGate {
    private final NandGate nandGate = new NandGate();

    /**
     * and(a, b) = not(not(and(a, b))) = not(nand(a, b))
     */
    public boolean calc(boolean a, boolean b) {
        boolean nandResult = nandGate.calc(a, b);
        return nandGate.calc(nandResult, nandResult);
    }
}

src/main/java/org/example/OrGate.java ⬇️

java 复制代码
package org.example;

public class OrGate {
    private final NandGate nandGate = new NandGate();

    /**
     * or(a, b)
     * = not(not(or(a, b)))
     * = not(not(a) & not(b))
     * = not(nand(a) & nand(b))
     * = nand(nand(a), nand(b))
     */
    public boolean calc(boolean a, boolean b) {
        boolean notA = nandGate.calc(a, a);
        boolean notB = nandGate.calc(b, b);
        return nandGate.calc(notA, notB);
    }
}

src/test/java 目录下的各个文件

src/test/java 目录下有如下 4java 文件

  • src/test/java/org/study/NandGateTest.java
  • src/test/java/org/study/NotGateTest.java
  • src/test/java/org/study/AndGateTest.java
  • src/test/java/org/study/OrGateTest.java

它们的内容如下 ⬇️

src/test/java/org/study/NandGateTest.java ⬇️

java 复制代码
package org.study;

import org.example.NandGate;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.TestClass;

import java.util.List;

public class NandGateTest {

    private final NandGate nandGate = new NandGate();

    /**
     * nand(true, true) => false
     */
    @Test
    public void test_true_true() {
        Assert.assertFalse(nandGate.calc(true, true));
    }

    /**
     * nand(true, false) => true
     */
    @Test
    public void test_true_false() {
        Assert.assertTrue(nandGate.calc(true, false));
    }

    /**
     * nand(false, true) => true
     */
    @Test
    public void test_false_true() {
        Assert.assertTrue(nandGate.calc(false, true));
    }

    /**
     * nand(false, false) => true
     */
    @Test
    public void test_false_false() {
        Assert.assertTrue(nandGate.calc(false, false));
    }

    public static void main(String[] args) {
        // We can set a breakpoint and observe how TestClass finds @Test-annotated methods with next two lines of code
        TestClass testClass = new TestClass(NandGateTest.class);
        List<FrameworkMethod> annotatedMethods = testClass.getAnnotatedMethods(Test.class);
    }
}

src/test/java/org/study/NotGateTest.java ⬇️

java 复制代码
package org.study;

import org.example.NotGate;
import org.junit.Assert;
import org.junit.Test;

public class NotGateTest {

    private final NotGate notGate = new NotGate();

    /**
     * not(true) => false
     */
    @Test
    public void test_true() {
        Assert.assertFalse(notGate.calc(true));
    }

    /**
     * not(false) => true
     */
    @Test
    public void test_false() {
        Assert.assertTrue(notGate.calc(false));
    }
}

src/test/java/org/study/AndGateTest.java ⬇️

java 复制代码
package org.study;

import org.example.AndGate;
import org.junit.Assert;
import org.junit.Test;

public class AndGateTest {

    private final AndGate andGate = new AndGate();

    /**
     * and(true, true) => true
     */
    @Test
    public void test_true_true() {
        Assert.assertTrue(andGate.calc(true, true));
    }

    /**
     * and(true, false) => false
     */
    @Test
    public void test_true_false() {
        Assert.assertFalse(andGate.calc(true, false));
    }

    /**
     * and(false, true) => false
     */
    @Test
    public void test_false_true() {
        Assert.assertFalse(andGate.calc(false, true));
    }

    /**
     * and(false, false) => false
     */
    @Test
    public void test_false_false() {
        Assert.assertFalse(andGate.calc(false, false));
    }

}

src/test/java/org/study/OrGateTest.java ⬇️

java 复制代码
package org.study;

import org.example.OrGate;
import org.junit.Assert;
import org.junit.Test;

public class OrGateTest {

    private final OrGate orGate = new OrGate();

    /**
     * or(true, true) => true
     */
    @Test
    public void test_true_true() {
        Assert.assertTrue(orGate.calc(true, true));
    }

    /**
     * or(true, false) => true
     */
    @Test
    public void test_true_false() {
        Assert.assertTrue(orGate.calc(true, false));
    }

    /**
     * or(false, true) => true
     */
    @Test
    public void test_false_true() {
        Assert.assertTrue(orGate.calc(false, true));
    }

    /**
     * or(false, false) => false
     */
    @Test
    public void test_false_false() {
        Assert.assertFalse(orGate.calc(false, false));
    }

}

小结

目前已经出现了三个重要的类 👇

主要作用 javadoc 截图
TestClass \text{TestClass} TestClass 对测试类进行封装,通过 TestClass 可以找到带有指定注解的字段/方法
Runner \text{Runner} Runner 负责运行测试
ParentRunner \text{ParentRunner} ParentRunner 如果我们将一个 Runner 视为亲子结构,则可以让这个 Runner 继承 ParentRunner. 典型的子类有 BlockJUnit4ClassRunner Suite !

这三个类的 Fully Qualified Class Name 列举如下 👇

Fully Qualified Class Name
TestClass \text{TestClass} TestClass org.junit.runners.model.TestClass \text{org.junit.runners.model.TestClass} org.junit.runners.model.TestClass
Runner \text{Runner} Runner org.junit.runner.Runner \text{org.junit.runner.Runner} org.junit.runner.Runner
ParentRunner \text{ParentRunner} ParentRunner org.junit.runners.ParentRunner \text{org.junit.runners.ParentRunner} org.junit.runners.ParentRunner

其他

"要点"里的思维导图是如何画出来的?

我是用 PlantUML 画的,代码如下

pxml 复制代码
@startmindmap
'https://plantuml.com/mindmap-diagram

caption <i>Runner</i> 如何找到并运行带有 <i>@Test</i> 注解的方法

* 某个测试类 <i>T</i>
** <i>T</i> 对应的 <i>Runner</i>: <i>Runner<sub>T</sub></i>
*** <i>Runner<sub>T</sub></i> 持有 <i>T</i> 对应的 <i>TestClass</i>: <i>TestClass<sub>T</sub></i>
***:通过 <i>TestClass<sub>T</sub></i> 可以找到 <i>T</i> 里
带有 <i>@Test</i> 注解的方法
<i>method<sub>1</sub>, method<sub>2</sub>, ...</i>;
***:当 <i>Runner<sub>T</sub></i> 的 <i>getChildren()</i> 方法
被调用时返回 <i>method<sub>1</sub>, method<sub>2</sub>, ...</i>;

center footer 掘金技术社区@金銀銅鐵

@endmindmap

参考资料

相关推荐
土狗TuGou5 分钟前
SQL内功笔记 · 第6篇:窗口函数的使用ROW_NUMBER等
java·数据库·后端·sql·mysql
Chase_______7 分钟前
【Java基础核心知识点全解·09】Java 内存布局与垃圾回收详解:栈、堆、栈帧、GC Roots 与对象回收
java·开发语言
武子康10 分钟前
Java-11 深入浅出 MyBatis 一级缓存详解:从原理到失效场景 Executor
java·后端
川石课堂软件测试10 分钟前
使用mock进行接口测试教程
数据库·python·功能测试·测试工具·华为·单元测试·appium
寻道码路24 分钟前
LangChain4j Java AI 应用开发实战(十):Embedding 模型与文本分类 - 语义向量化
java·人工智能·ai·embedding
折哥的程序人生 · 物流技术专研27 分钟前
Java 23 种设计模式:从踩坑到精通 | 抽象工厂 —— 支付/收款如何成套创建?跨平台 UI 如何一键换肤?
java·开发语言·后端·设计模式
方也_arkling30 分钟前
【Java-Day11】抽象类和抽象方法
java·开发语言
XS03010634 分钟前
并发编程 七
java
YikNjy1 小时前
string(c++)
java·服务器·c++
小江的记录本1 小时前
【Spring AI】Spring AI中RAG误触发与系统提示词泄露问题解决方案(完整版+代码方案)
java·人工智能·spring boot·后端·python·spring·面试