Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit4 : Test a shutdown hook is called

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 ?

like image 935
Rémi Doolaeghe Avatar asked May 21 '13 13:05

Rémi Doolaeghe


People also ask

How do you test a shutdown hook?

getRuntime(). removeShutdownHook(Thread) method. Its boolean return value indicates if the respective thread was a registered hook previously. Thus, one can test if the hook' run() method performs correctly as one part of a test.

When shutdown hook is called?

Shutdown hooks are called when the application terminates normally (when all threads finish, or when System. exit(0) is called).

What is shutdown hook in thread?

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.


1 Answers

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.

like image 183
Duncan Jones Avatar answered Oct 20 '22 16:10

Duncan Jones