Prashant Pandey
Prashant Pandey

Reputation: 4642

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?

Upvotes: 4

Views: 3015

Answers (2)

esukanovic
esukanovic

Reputation: 26

Don't know what does your "infinite loop" look like but for consuming Kafka messages/events I suggest you to take a look at KafkaListener. By doing so you can more easily write your integration test.

"I don't want to modify my application just so that I can test them." - actually, you should rewrite your code in order to be able to test it :)

Upvotes: 0

Balajee
Balajee

Reputation: 191

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.

Upvotes: 3

Related Questions