michealAtmi
michealAtmi

Reputation: 1042

How to set static variable on object before all junits

Hi I have thousands of junits, many of them are using MyFactory.someId which is a static field. In production it is set by Spring Boot Application class in run method. How could I set it before junits start to run and not change each of those thousand junits ? Is it possible to implement something like BeforeAllJunitsFromAllClassesStart and then set a static field ? Or static variables are cleaned before each class with tests starts to run?

Upvotes: 2

Views: 411

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44980

Define a TestExecutionListener which will be invoked once per test suite execution. You will be able to run your initialisation code before any of the tests starts. That's how Spring Boot does it with SpringBootDependencyInjectionTestExecutionListener and other.

This may get a bit more complex if you use different runners e.g. different JUnit4 @RunWith annotation configs or different JUnit5 engines, because listeners are invoked as part of the runner/engine. In this case you may want to refactor the tests to share a parent class which does the setup.

Upvotes: 1

Related Questions