junit在main线程执行结束时就会退出执行

junit在main线程执行结束时就会退出执行

junit不支持多线程测试,junit在main线程执行结束时就会退出执行
至于为什么会这样,网络上找了一些文章:

// junit.textui.TestRunner#main
public static void main(String args[]) {
    TestRunner aTestRunner = new TestRunner();
    try {
        // 开始执行测试代码
        TestResult r = aTestRunner.start(args);
        // 比较结果: 不管失败还是成功都exit()
        if (!r.wasSuccessful()) {
            System.exit(FAILURE_EXIT);
        }
        System.exit(SUCCESS_EXIT);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        System.exit(EXCEPTION_EXIT);
    }
}

但我实际使用的是idea 的插件com.intellij.rt.junit,执行逻辑有点不同,并没有执行到上文的main方法里,debug了一番后,发现在下文代码中捕捉到了断点:

//org.junit.runner.JUnitCore#run(org.junit.runner.Runner)
public Result run(Runner runner) {
    Result result = new Result();
    RunListener listener = result.createListener();
    notifier.addFirstListener(listener);
    try {
        notifier.fireTestRunStarted(runner.getDescription());
        runner.run(notifier);
        notifier.fireTestRunFinished(result);
    } finally {
        removeListener(listener);
    }
    return result;
}

但是,万恶的闭源项目,我看不到源码了:

image-20210112194946989

再往上的代码调用时idea插件的代码,GitHub上、idea官方文档里找了一番后还是没有找到。

最后受上文代码的启发,在java.lang.System#exit处打了断点,果然有执行到这个代码:

image-20210112195103300

虽然由于万恶的闭源代码还是看不了发生了什么

image-20210112195215490

但经过测试还是可以得到结论: junit在main线程执行结束时就会退出执行。测试代码如下;

@Test
public void test_RunnableThread() {
    Thread thread = new Thread(new Runnable() {
        @Override
        @SneakyThrows
        public void run() {
            Thread.sleep(1_000);
            // 这句话不会输出
            System.out.println("虽然我是用户线程,但我还是不能执行,因为junit只关心main线程...呜呜呜");
        }
    });
    thread.setDaemon(false);
    thread.start();
    // main线程执行结束后直接退出了
}

没有输出结果。


这篇博客启发:我把idea的安装目录翻了一遍

image-20210113105335235

图中所有可以的junit相关的代码都在这里,并没有那篇博文中的junit.rt.jar,怀着试一试的心态,我把这些包都导入到项目中,下图的操作界面是Project Structure:

image-20210113105554043

导入之后全局搜索类JUnitStarter,没有结果。

好吧,黔驴技穷耳。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值