1. Introduction
In our tutorial on testing in Spring Boot, we saw how we can use the @DataJpaTest annotation.
In this next tutorial, we’ll see how to resolve the error “Unable to find a @SpringBootConfiguration“**.**
2. Causes
The @DataJpaTest annotation helps us to set up a JPA test. For this, it initializes the application, ignoring irrelevant parts. For instance, it’ll ignore MVC controllers.
However, to initialize the application it needs configuration.
For this, it searches in the current package and goes up in the package hierarchy until a configuration is found.
For example, let’s add a @DataJpaTest in the com.baeldung.data.jpa package*.* Then, it’ll search for a configuration class in:
- com.baeldung.data.jpa
- com.baeldung.data
- and so on
However, when no configuration is found, the application will report an error:
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...)
with your test java.lang.IllegalStateException
This could, for example, happen because the configuration class is located in a more specific package, like com.baeldung.data.jpa.application.
Let’s move the configuration class to com.baeldung.data.jpa. As a result, Spring will now be able to find it.
On the other hand, we can have a module that doesn’t have any @SpringBootConfiguration. In the next section, we’ll look into this scenario.
3. Missing @SpringBootConfiguration
What if our module doesn’t contain any @SpringBootConfiguration? There can be multiple reasons for that. Let’s assume, for this tutorial, that we have a module containing only model classes.
So, the solution is straightforward. Let’s add a @SpringBootApplication to our test code:
@SpringBootApplication
public class TestApplication {}
Now that we have an annotated class, Spring is able to bootstrap our tests.
To validate our setup, let’s inject a TestEntityManager and validate that it is set:
@RunWith(SpringRunner.class)
@DataJpaTest
public class DataJpaUnitTest {
@Autowired
TestEntityManager entityManager;
@Test
public void givenACorrectSetup_thenAnEntityManagerWillBeAvailable() {
assertNotNull(entityManager);
}
}
This test succeeds when Spring can find the @SpringBootConfiguration in its own package or one of its parent packages.
4. Conclusion
In this short tutorial, we looked into two different causes for the error: “Unable to find a @SpringBootConfiguration“.
First, we looked at a case where the configuration class could not found. This was because of its location. We solved it by moving the configuration class to another location.
Second, we looked at a scenario where no configuration class was available. We resolved this by adding a @SpringBootApplication to our test codebase.
As always, the full source code of the article is available over on GitHub.