4

Let's consider the following test:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleTest {

    static {
        System.out.println("hello from static");
    }

    @BeforeAll
    static void beforeAll() {
        System.out.println("before all!");
    }

    @Test
    void contextLoads() {
        System.out.println("hello!");
    }
}

I would expect that first, the class loader loads the class and static functions are called. Then the object is instantiated and spring-boot context loads.

Instated, I see in logs:

...

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.0.4)

(...)

hello from static
before all!

I think in Spring Boot 2.7.x it used to work as I expect but after migrating to Spring Boot 3 the outcome is as presented above.

It comes down to the question: how to run any code before Spring Boot starts loading the context?

szakal
  • 127
  • 1
  • 1
  • 6
  • 1
    You've annotated the class with `@SpringBootTest`. The class can't load until Spring Boot has loaded. If you want to run code before Spring Boot, you can't have it as part of the Spring configuration. – tbatch Mar 22 '23 at 14:15
  • ok, thx. but has it changed? I don't see any info in spring boot's migration guides. so far it worked without any issues. The problem is I have to start a wiremock before the context is loaded. and so far I was doing it using @BeforeAll annotation, but after bumping the version it stopped working – szakal Mar 22 '23 at 17:32
  • Which JUnit version are you using? Maybe whichever version you’re using (to get @BeforeAll) is not a compatible dependency of Spring Boot 3, which I believe requires Java 17. – Woodchuck Mar 22 '23 at 19:24
  • I'm not specifing junit version so I guess it's compatible with spring-boot3. And it's: 5.9.2. I think, what happens is: spring test runner reads the main class with the context, it starts context initialization and then loads the test class. However, as I mentioned it used to work differently. I managed to hack it and move my initialization to static{} block in the main class which obviously has lots of drawbacks, but I managed to spin wiremock before the context. However, there must be a more elegant solution.. – szakal Mar 24 '23 at 07:59

0 Answers0