Unable to find a @SpringBootConfiguration when running a test
I’m getting the following error when I try to run by Spring Boot test classes.
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test java.lang.IllegalStateException
How to fix this issue?
Spring Boot can’t find
@SpringBootConfiguration in the current or top-level packages
The Spring Boot tests, that is the classes that you annotate with
@DataJpaTest, need to find your application’s configuration class that’s marked with
SpringBootApplication). If it can’t find this class, it throws the above error.
Now the question is: How do test classes find or look for the
@SpringBootConfiguration class? The answer is simple. Suppose your test class is in the
com.codeahoy.myapp.controllers package. Spring Boot will first try to find if the configuration class exists in the same package as your tests. If it cannot find it, it goes one package up in the hierarchy and looks for it there, that is,
com.codeahoy.myapp. It keeps traversing the package hierarchy this way until it finds the class or throws an error if it reaches the base package (
com) and still can’t find it there.
In the above example, if your configuration class exists in another package e.g.
com.codeahoy.myapp.config, the test defined in package
com.codeahoy.myapp.controllers won’t be able to find it because Spring Boot won’t search it in there.
To fix, you can move your
SpringBootApplication) higher up in the hierarchy (I always place it in the base package i.e.
com.codeahoy.myapp) so rest of the packages can easily find it.
If moving classes isn’t feasible, you can use the
@SpringBootTest(classes = App.class) annotation in your test class to specify the location of the configuration class. In this case,
App.class is the configuration class.
Hope this helped!