JUnit - 自定义 Rule

一、自定义 Rule

1、Custom Rule
java 复制代码
public class CustomTestRule implements TestRule {

    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {

            @Override
            public void evaluate() throws Throwable {
                // 测试执行前
                beforeTest(description);
                try {
                    // 测试执行
                    base.evaluate();
                    // 测试成功
                    onTestSuccess(description);
                } catch (Throwable t) {
                    // 测试失败
                    onTestFailure(description, t);
                    throw t;
                } finally {
                    // 无论测试成功失败
                    afterTest(description);
                }
            }
        };
    }

    private void beforeTest(Description description) {
        System.out.println("开始测试: " + description.getMethodName());
    }

    private void onTestSuccess(Description description) {
        System.out.println("测试通过: " + description.getMethodName());
    }

    private void onTestFailure(Description description, Throwable t) {
        System.out.println("测试失败: " + description.getMethodName() + " - " + t.getMessage());
    }

    private void afterTest(Description description) {
        System.out.println("测试结束: " + description.getMethodName());
    }
}
2、Test
java 复制代码
public class CustomTestRuleTest {

    @Rule
    public CustomTestRule customTestRule = new CustomTestRule();

    @Test
    public void test() {
        System.out.println("执行测试逻辑...");
    }
}
复制代码
# 输出结果

开始测试: test
执行测试逻辑...
测试通过: test
测试结束: test

二、实例实操(重试 Rule)

1、Custom Rule
java 复制代码
public class RetryRule implements TestRule {

    private final int maxRetries;

    public RetryRule(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {

            @Override
            public void evaluate() throws Throwable {
                for (int attempt = 1; attempt <= maxRetries; attempt++) {
                    try {
                        System.out.printf("第 %d / %d 次尝试执行测试: %s%n", attempt, maxRetries, description.getMethodName());
                        base.evaluate();
                        System.out.printf("第 %d 次执行测试成功%n", attempt);
                        return;
                    } catch (Throwable e) {
                        System.err.printf("第 %d 次执行测试失败: %s%n", attempt, e.getMessage());
                        if (attempt < maxRetries) {
                            waitBeforeRetry(attempt);
                            continue;
                        }
                        throw e; // 超过最大重试次数,抛出异常
                    }
                }
            }
        };
    }

    private void waitBeforeRetry(int attempt) throws InterruptedException {

        // 指数退避策略
        long waitTime = Math.min(1000 * (long) Math.pow(2, attempt - 1), 10000);
        System.out.printf("等待 %dms 后重试...%n", waitTime);
        Thread.sleep(waitTime);
    }
}
2、Test
java 复制代码
public class RetryRuleTest {

    @Rule
    public RetryRule retryRule = new RetryRule(3);

    @Test
    public void test() {
        System.out.println("执行测试逻辑...");
    }
}
复制代码
# 输出结果

第 1 / 3 次尝试执行测试: test
执行测试逻辑...
第 1 次执行测试成功
java 复制代码
public class RetryRuleTest {

    @Rule
    public RetryRule retryRule = new RetryRule(3);

    @Test
    public void test() {
        int a = 10 / 0;
    }
}
复制代码
# 输出结果

第 1 / 3 次尝试执行测试: test
第 1 次执行测试失败: / by zero
等待 1000ms 后重试...
第 2 / 3 次尝试执行测试: test
第 2 次执行测试失败: / by zero
等待 2000ms 后重试...
第 3 / 3 次尝试执行测试: test
第 3 次执行测试失败: / by zero

三、关于异常重新抛出

java 复制代码
public class CustomTestRule implements TestRule {

    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {

            @Override
            public void evaluate() throws Throwable {
                beforeTest(description);
                try {
                    base.evaluate();
                    onTestSuccess(description);
                } catch (Throwable t) {
                    onTestFailure(description, t);

                    // 异常重新抛出
                    throw t;
                } finally {
                    afterTest(description);
                }
            }
        };
    }

    private void beforeTest(Description description) {
        System.out.println("开始测试: " + description.getMethodName());
    }

    private void onTestSuccess(Description description) {
        System.out.println("测试通过: " + description.getMethodName());
    }

    private void onTestFailure(Description description, Throwable t) {
        System.out.println("测试失败: " + description.getMethodName() + " - " + t.getMessage());
    }

    private void afterTest(Description description) {
        System.out.println("测试结束: " + description.getMethodName());
    }
}
  1. 异常重新抛出确保了失败信息能传递到 JUnit 框架,如果不抛出,即使测试方法失败了,也会显示为成功状态

  2. TestRule 只是增强测试,而不是替代测试框架的错误处理

  3. 异常重新抛出保持测试的原始语义,只是在执行前后添加了额外的逻辑

相关推荐
2401_832402752 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
Remember_9932 小时前
Spring 中 REST API 调用工具对比:RestTemplate vs OpenFeign
java·网络·后端·算法·spring·php
Y_032 小时前
浅谈Java虚拟机JVM
java·开发语言·jvm
TheNextByte12 小时前
在小米上检索照片/视频的5种方法
android
阿杰 AJie2 小时前
使用Iterator迭代器在遍历中安全删除元素
java·spring
showker2 小时前
Mac mini-macOS Tahoe 26.1-安装ftp服务-用户名密码都对,就是提示530 login incorrect
linux·服务器·数据库
电商API&Tina2 小时前
【电商API】淘宝/天猫拍立淘(按图搜索商品)API 全解析
大数据·开发语言·数据库·人工智能·json·图搜索算法
m0_706653232 小时前
自动化与脚本
jvm·数据库·python
XerCis2 小时前
Python读取硬盘信息pySMART——调用smartctl
开发语言·python·硬件架构