It appears that Spring and JUnit don't directly have anything to do this. After some more googling, I found a few bits that lead to some inspiration.
Making use of a custom rule extending ExternalResource
(from JUnit), I'm kind of bastardizing it, but it does what I want:
public class MyRule extends ExternalResource {
static private MyRule instance;
static public MyRule get() {
if (instance == null) {
instance = new MyRule();
}
return instance;
}
private MyRule() {
// do init stuff
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// do shutdown stuff
});
}
}
The basic idea is that the rule is a singleton. In each class that might need it, I'd put an @ClassRule
:
public class MyTest {
@ClassRule
private MyRule myRule = MyRule.get();
}
It'll lazy-initialize itself, which will do all of the setup needed. It'll also register a shutdown hook, which will then handle any after stuff.
With this pattern, it'll run code exactly once before any tests (that need this rule) run, and it'll perform shutdown code only at the very end after all tests have finished.
Note: It purposely doesn't override the before()
and after()
functions, because those are before and after each class. You could add things there if you wanted to do something in between classes as well.