-2

I have a simple JUnit test which is ran by Maven through a method marked by @Test annotation. I want to place the shutdown hook into that test because I want to print some test results if the user hits CTRL-C. I code the following lines:

@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 ...

}

To run it I use Maven:

mvn clean test -DtestClassName=com.MyTest

The problem is that nothing is printed. Looks like System.out.println is not working already. What can I do to fix it?

KutaBeach
  • 1,445
  • 21
  • 43

1 Answers1

1

I've tried to write the unit test for simulating your case as the following

@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");
}

I try to execute with mvn clean test -Dtest=MyTest and then hit the Ctrl+C, It shows me as

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

If I wait for the sleeping period, it shows me as

-------------------------------------------------------
 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

I hope this may help.

Charlee Chitsuk
  • 8,847
  • 2
  • 56
  • 71