JUnit4 : Test a shutdown hook is called
Asked Answered
F

3

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 ?

Frances answered 21/5, 2013 at 13:3 Comment(0)
W
10

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.

Wolfenbarger answered 21/5, 2013 at 13:9 Comment(1)
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 youAnsilme
I
0

In addition to Duncans answer I'd like to point out the Runtime.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. As a second part one can call Runtime.getRuntime().removeShutdownHook(Thread)` and assert that the thread was actually registered as a hook.

Together, the two tests assure the overall functioning of the shutdown hook.

Incalescent answered 9/7, 2021 at 10:12 Comment(0)
T
0

You should try and spawn that process in your test, and verify its output somehow, confirming that the shutdown hook executed.

It would be nice to simulate it in test, but I don't think that's possible.

Remember that writing tests that spawn the process would actually be the best for a lot of usages, except maybe speed - that's why we write tests that work right from within the code itself.

Twelve answered 26/5, 2023 at 15:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.