Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Test Main Thread Gets Stuck in Application's Infinite Loop

I am writing an integration test for one of my applications. I have the following annotations on the test class:

@SpringBootTest(
    classes = {Application.class, ApplicationConfig.class})

My application is a normal spring boot application that is triggered by the ApplicationReadyEvent. It contains an infinite loop (to poll kafka).

The problem is, since it is an infinite loop, the main thread never comes and my tests don't move forward. A 'solution' can be running the loop in a different thread, but I don't want to modify my application just so that I can test them.

Is there a better way to do this?

like image 262
Prashant Pandey Avatar asked Sep 16 '25 04:09

Prashant Pandey


1 Answers

You need to understand the lifecycle of spring boot test & tests in general. When you annotate a class with SpringBootTest -> Spring Boot scans for all the appropriates beans that need to be created and literally brings the entire application up within the scope of the test. Since it is a heavy process, it ensures the application context can be reused.

Now coming to how the application comes up, it follows the typical spring boot lifecycle. When you run the spring boot jar, the main class is actually - "org.springframework.boot.loader.JarLauncher" which in its main method scans the entire classpath, creates the appropriate beans and invokes the main method of the class annotated with SpringApplication. In the test lifecycle, a similar process is followed and the spring application is started. Further to which the "ApplicationReady" method is invoked on the same thread as the test executor and since there is a while loop, it blocks further execution.

like image 125
Balajee Avatar answered Sep 18 '25 17:09

Balajee