How can I run code in my @RunWith(SpringRunner.class)
@SpringBootTest(classes = {...})
JUnit test before Spring starts?
This question has been asked several times (e.g. 1, 2) but was always "solved" by some configuration recommendation or other, never with a universal answer. Kindly don't question what I am about to do in that code but simply suggest a clean way to do it.
Tried so far and failed:
Extend SpringJUnit4ClassRunner
to get a class whose constructor can run custom code before initializing Spring. Failed because super(testClass)
must be called first thing and already does a whole lot of things that get in the way.
Extend Runner
to get a class that delegates to SpringRunner
instead of inheriting it. This class could run custom code in its constructor before actually instantiating the SpringRunner. However, this setup fails with obscure error messages like java.lang.NoClassDefFoundError: javax/servlet/SessionCookieConfig. "Obscure" because my test has no web config and thus shouldn't meddle with sessions and cookies.
Adding an ApplicationContextInitializer
that is triggered before Spring loads its context. These things are easy to add to the actual @SpringApplication, but hard to add in Junit. They are also quite late in the process, and a lot of Spring has already started.