【问题标题】:Shutdown hook is not printing to console in JUnit Test executed via Maven关闭挂钩未打印到通过 Maven 执行的 JUnit 测试中的控制台
【发布时间】:2013-03-17 10:02:17
【问题描述】:

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

【问题讨论】:

  • 仅将该代码放入 main() 会打印出 hooked。您能否展示一个产生相同行为的完整示例?
  • 为我工作。我认为我们需要一个 SSCCE (sscce.org)。
  • 你在你的代码中写过main()方法吗?
  • 正如我的帖子中提到的,我调用了带有@Test 注释的方法(通过 Maven),我没有调用 main() 方法。
  • 如果我错了,请纠正我。我知道该命令可能是mvn clean test -Dtest=com.MyTest,正如maven.apache.org/surefire/maven-surefire-plugin/examples/…中提到的那样

标签: java maven logging junit shutdown-hook


【解决方案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

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2018-04-15
    • 2017-01-14
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    相关资源
    最近更新 更多