JUnit4 Statement 链式调用

JUnit4源码解读

其中

直接看代码

//BlockJUnit4ClassRunner.class
    protected Statement methodBlock(final FrameworkMethod method) {
        Object test;
        try {
            test = (new ReflectiveCallable() {
                protected Object runReflectiveCall() throws Throwable {
                    return BlockJUnit4ClassRunner.this.createTest(method);
                }
            }).run();
        } catch (Throwable var4) {
            return new Fail(var4);
        }

        Statement statement = this.methodInvoker(method, test);
        statement = this.possiblyExpectingExceptions(method, test, statement);
        statement = this.withPotentialTimeout(method, test, statement);
        statement = this.withBefores(method, test, statement);
        statement = this.withAfters(method, test, statement);
        statement = this.withRules(method, test, statement);
        statement = this.withInterruptIsolation(statement);
        return statement;
    }

//调用
    protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
        Description description = this.describeChild(method);
        if (this.isIgnored(method)) {
            notifier.fireTestIgnored(description);
        } else {
            Statement statement = new Statement() {
                public void evaluate() throws Throwable {
                    BlockJUnit4ClassRunner.this.methodBlock(method).evaluate();
                }
            };
            this.runLeaf(statement, description, notifier);
        }

    }

为什么就可以链式触发呢 其实看源码中的

    protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) {
        List<FrameworkMethod> afters = this.getTestClass().getAnnotatedMethods(After.class);
        return (Statement)(afters.isEmpty() ? statement : new RunAfters(statement, afters, target));
    }
  
    public RunAfters(Statement next, List<FrameworkMethod> afters, Object target) {
        this.next = next;
        this.afters = afters;
        this.target = target;
    }

是因为在next储存了statement,并且在自己的evaluate中写入了next.evaluate,这样就可以一层一层调用了各个evaluate了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值