15

I have a method which adds a shutdown hook. I need to test (via JUnit) that the code executed in the hook is called :

public void myMethod(){
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            ... code to test ...
        }
    });
}

How can I simulate a shutdown in my unit test ?

Rémi Doolaeghe
  • 2,034
  • 3
  • 26
  • 45

1 Answers1

9

I don't think you'll be able to test that. Instead, just test that your code behaves correctly when invoked (by unit testing it separately). Then, trust that Java will invoke your code at the right time.

I.e. extract your code into a separate class that extends Thread and test the behaviour by executing run() in a unit test.

Duncan Jones
  • 59,308
  • 24
  • 169
  • 227
  • If I have no better solution, I'll test my code the way you explained, and will write another test that mocks the method adding the hook to ensure it is called whenever is has to be. Thank you – Rémi Doolaeghe May 21 '13 at 13:18