How to solve Unable to find a @SpringBootConfiguration in your Test

When running Spring Boot tests using annotations like @SpringBootTest or @DataJpaTest, Spring Boot needs to find the main configuration class (annotated with @SpringBootApplication or @Configuration) to set up the application context properly. If Spring Boot cannot find the configuration class, it throws the error “Unable to find a @SpringBootConfiguration,” and the tests fail to execute.

This is a very common error in a SpringBoot application:

Unable to find a @SpringBootConfiguration,
	you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

In practice, your Test class is unable to find a @SpringBootConfiguration Class therefore it fails.

The Common Cause of the Issue

The most common cause of this issue is that the main configuration class might not be in the same package or a sub-package that Spring Boot automatically scans.. For example:

How to solve Unable to find a @SpringBootConfiguration

As you can see from the above Spring Boot project, the Application Class is in the rest.clients package while the Test Class is in the rest.example namespace.

How to fix it

There are couple of ways to solve the problem:

Ensure that your main configuration class is in a package that Spring Boot automatically scans during component scanning. By default, Spring Boot scans the package where the main class is located and its sub-packages.

For example:

Unable to find a @SpringBootConfiguration

By using the same package both in the Application Class and in the Test Class will solve the issue.

Another option is to specify the classes attribute in the @SpringBootTest or @DataJpaTest annotation.

@SpringBootTest(classes = ClientsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ClientsApplicationTests {

	
}

Clearly, you need to import the Classes from your Test.

Conclusion:

In this tutorial, we explored the common causes of the “Unable to find a @SpringBootConfiguration” issue in Spring Boot tests. We provided solutions to fix the problem. By following these solutions, you can successfully run Spring Boot tests without encountering the mentioned error and verify the behavior of your Spring Boot application.