美文网首页
Junit测试多线程时候的注意事项

Junit测试多线程时候的注意事项

作者: 雨夏_ | 来源:发表于2019-04-22 16:09 被阅读0次

    问题:我使用Junit进行测试的时候,发现发送邮件的功能偶尔会出现发送失败的问题,而且没有任何提示。

    出现问题代码:

    executor.execute(new Runnable() {
        @Override
        public void run() {
            String content="测试";
            eMailService.sendEMail(receiveMailList, "测试", content);
        }
    });
    

    这段代码偶然不起作用,邮件服务我进行了测试,保证了邮件服务的可靠性,先排除邮件服务的出问题的可能。

    猜测可能的原因:Junit进行测试的时候,主线程结束会导致子线程也终止。

    首先进行一项测试:

    @Test
    public void test() throws InterruptedException {
        System.out.println("test start");
        new Thread(new Runnable() {
            int i=0;
            @Override
            public void run() {
                while (i<100){
                    System.out.println(i++);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        //主线程睡10s,子线程就会输出10次(不保证一定10次),主线程执行完毕后,子线程也会停止输出
        Thread.sleep(10000);
        System.out.println("test end");
    }
    

    测试结果:

    test start
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    test end
    

    很明显当主进程结束了,子进程也会随后结束 。

    分析一下Junit底层代码做了一些什么:

    public static void main(String args[]) {
        TestRunner aTestRunner = new TestRunner();
        try {
            TestResult r = aTestRunner.start(args);
            if (!r.wasSuccessful()) {
                System.exit(FAILURE_EXIT);
            }
            System.exit(SUCCESS_EXIT);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(EXCEPTION_EXIT);
        }
    }
    

    这是Junit运行的入口,我们可以发现,不管Junit测试是否成功,都会调用System.exit(),而这个方法会用来结束当前正在运行的java虚拟机。当status=0时表示正常结束,status=1表示异常退出(强制退出,程序未执行完也会退出)。JVM都关闭了,子线程还靠什么运行呢?所以这就是问题所在。

    如果我们测试的时候,点击的是下图的中的按钮进行Junit测试,使用的是Intellij提供的JUnitStarter进行启动测试的。


    JUnitStarter中的main方法如下(源码链接):
    public static void main(String[] args) throws IOException {
        Vector argList = new Vector();
        for (int i = 0; i < args.length; i++) {
          String arg = args[i];
          argList.addElement(arg);
        }
    
        final ArrayList listeners = new ArrayList();
        final String[] name = new String[1];
    
        String agentName = processParameters(argList, listeners, name);
    
        if (!JUNIT5_RUNNER_NAME.equals(agentName) && !canWorkWithJUnitVersion(System.err, agentName)) {
          System.exit(-3);
        }
        if (!checkVersion(args, System.err)) {
          System.exit(-3);
        }
    
        String[] array = new String[argList.size()];
        argList.copyInto(array);
        int exitCode = prepareStreamsAndStart(array, agentName, listeners, name[0]);
        System.exit(exitCode);
      }
    

    从这段源码中可以发现,最终也会调用System.exit()。

    总结:在使用了多线程,需要测试的时候,不要使用junit进行测试,否则就会出现以上问题。如果非要使用junit测试,需要保证主线程在子线程执行完毕后再结束。可以使用thread.join(),或者一些并发包中的一些类来使主线程等待子线程执行完毕。

    相关文章

      网友评论

          本文标题:Junit测试多线程时候的注意事项

          本文链接:https://www.haomeiwen.com/subject/ohfugqtx.html