在通过Maven执行的JUnit Test中,关闭挂钩不会打印到控制台

时间:2013-03-27 10:41:50

标签: java maven logging junit shutdown-hook

我有一个简单的JUnit测试,由Maven通过@Test注释标记的方法运行。我想将关闭钩子放入该测试中,因为如果用户点击CTRL-C,我想打印一些测试结果。我编写以下代码:

@Test
public void runTest() {
    Thread shutdownHook = new Thread()
    {
        @Override
        public void run()
        {
            System.out.println("hooked");
            ... print something via System.out.println ...
        }
    };
    Runtime.getRuntime().addShutdownHook(shutdownHook);

    ... run test ...

}

要运行它,我使用Maven:

  

mvn clean test -DtestClassName = com.MyTest

问题在于没有打印任何内容。看起来System.out.println已经无效了。我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:1)

我已经尝试编写单元测试以模拟您的案例,如下所示

@Test
public void whenTest() {
    final Thread shutdownHook = new Thread()
    {
        @Override
        public void run()
        {
            System.out.println("hooked");
        }
    };
    Runtime.getRuntime().addShutdownHook(shutdownHook);
    System.out.println("Start");
    try {
        Thread.sleep(10000);
    } catch (final InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Stop");
}

我尝试使用mvn clean test -Dtest=MyTest执行,然后点击Ctrl+C,它显示为

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.test.MyTest
Start
Terminate batch job (Y/N)? y

如果我等待睡眠时间,它会显示为

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.test.MyTest
Start
Stop
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.034 sec
hooked <----- Is this your expected?

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

我希望这可能有所帮助。