-2

我有一个简单的 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 还没有工作。我能做些什么来修复它?

4

1 回答 1

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

我希望这可能会有所帮助。

于 2013-03-27T12:21:58.213 回答