Skip to content
javahacks.dev
Testing

Fix Spring Boot Test Failed to Load ApplicationContext

Find why a Spring Boot test cannot load its ApplicationContext, from a missing configuration class to a missing bean, property or database.

6 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, JUnit5, Spring Security and Spring logos.

The test fails before its first line runs:

Text
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@1a2b3c testClass = dev.javahacks.shop.OrderControllerTest, ...]
	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(...)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: ...

Spring tries to start an application context for the test, and building it failed. This post lists the causes in the order to check them. The structure of the tests is described in a practical Java testing strategy, and the application side in Spring Boot from first project to production.

Read the last Caused by

Everything above it is the route Spring took. The innermost exception names the real problem, and the usual ones map to a section below:

Innermost messageSection
Unable to find a @SpringBootConfigurationCause 1
No qualifying bean of typeCause 2
Could not resolve placeholderCause 3
Failed to configure a DataSource, connection refusedCause 4

Cause 1: Spring cannot find the application class

Text
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration by searching packages up from test class 'dev.javahacks.tests.OrderTest'. You need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

Spring looks for the @SpringBootApplication class by walking up from the test's package. A test in dev.javahacks.tests cannot find an application in dev.javahacks.shop. Move the test into the application's package tree, or name the class:

java
@SpringBootTest(classes = ShopApplication.class)
class OrderTest { }

Cause 2: a slice does not load the bean

java
@WebMvcTest(OrderController.class)
class OrderControllerTest {
    // OrderController needs OrderService, which @WebMvcTest does not load
}

Provide the collaborator:

java
@MockitoBean OrderService orders;

For @DataJpaTest, services are not loaded either; import what you need with @Import(OrderRepositoryAdapter.class). The same message in a running application is no qualifying bean of type.

Cause 3: a property is missing

A test resource named application.properties or application.yaml replaces the main file on the test classpath. Properties that the application needs vanish. Rename the test file application-test.properties, activate it with @ActiveProfiles("test"), or set values inline:

java
@SpringBootTest(properties = "shop.currency=USD")

See the placeholder fix for the full list of reasons.

Cause 4: the database is not there

A full @SpringBootTest starts every auto-configured component, including the DataSource. Without a URL or a reachable database it fails. Use a Testcontainers PostgreSQL with @ServiceConnection, or exclude the data auto-configuration for tests that do not need it. A test that fails here only in CI is often missing Docker: Could not find a valid Docker environment.

Context caching can move the failure

Spring caches contexts between test classes by their configuration. A class that adds @MockitoBean or a @TestPropertySource creates a new context, and the cache keeps the old ones. If one context fails to build, the next class using the same configuration reports the same failure, which makes it look like many tests are broken when one setup is. Fix the first failure in the run.

Run one test alone

Shell
./mvnw -q test -Dtest=OrderControllerTest

If it passes alone and fails in the full run, a different test is changing shared state: a static field, a port, a file. Look for @DirtiesContext, which discards the cache and slows the suite; use it only when a test truly modifies the context.

Give the test a configuration that exists

A test that cannot find the application class fails in the first step. Name it, or move the test into the same package tree:

java
@SpringBootTest(classes = ShopApplication.class)
@ActiveProfiles("test")
class OrderControllerTest { }

@ActiveProfiles("test") loads application-test.properties on top of the main file, which is the right place for test overrides. A test whose package is outside the application's package is the other cause of the missing configuration, and the error then names Unable to find a @SpringBootConfiguration. The test's package should be the same or below the package of the class with @SpringBootApplication.

Supply properties and containers to the test

A test that needs a value that production gets from the environment can set it in the annotation or compute it at startup:

java
@SpringBootTest(properties = "app.api-key=test-key")
class ClientTest { }

@Testcontainers
@SpringBootTest
class RepositoryTest {

    @Container
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");

    @DynamicPropertySource
    static void datasource(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", db::getJdbcUrl);
        registry.add("spring.datasource.username", db::getUsername);
        registry.add("spring.datasource.password", db::getPassword);
    }
}

The registry accepts suppliers, so the properties are read after the container has started and its port is known. With Spring Boot 3.1 and later, @ServiceConnection replaces those lines for the common containers.

Slices and what they leave out

A slice loads a part of the context, and any bean outside it is missing unless you provide it. @WebMvcTest loads controllers, filters and converters, and no services or repositories. A controller that depends on a service fails with NoSuchBeanDefinitionException until the test supplies one:

java
@WebMvcTest(OrderController.class)
class OrderControllerTest {

    @MockitoBean
    OrderService service;
}

The mock fills the gap. A test with ten missing beans is a sign that the slice is the wrong tool, and @SpringBootTest with a real or fake service layer is better.

See the whole cause chain

The first lines of the exception are the same for every cause. The explanation is at the bottom. Surefire writes each test's full output to a file:

Shell
grep -n 'Caused by' target/surefire-reports/*OrderControllerTest.txt | tail -5

The last Caused by names the real problem, such as a missing property, an unsatisfied bean or a refused database connection. When only the summary is printed, rerun the one test with -Dsurefire.useFile=false to see the full trace in the console. For more detail on how the context was assembled, turn on logging.level.org.springframework.test.context=DEBUG.

Cached contexts hide and move failures

Spring caches a context between test classes that share the same configuration, so the first class to need it pays the cost and reports the failure. A different mix of properties, mocks or profiles creates a new context, and a suite can fail in a test unrelated to the change. @MockitoBean and @DirtiesContext both force new contexts. A suite with thirty distinct configurations starts thirty contexts and is slow, so group tests with the same setup, and prefer one shared base configuration.

Cause of a new contextHow to avoid it
Different @MockitoBean setsPut common mocks in a shared abstract class
@DirtiesContext on a methodReset state in @BeforeEach instead
Different properties stringsUse one application-test.properties
Different active profilesStandardise on one test profile

When one test passes alone and fails in the suite, an earlier test changed shared state, and the context cache is the first suspect.

A smoke test that guards the context

One test that starts the full context with the test profile is worth having in every project. It is quick to write, and it fails at once when someone adds a bean with a missing dependency or a property with no value. Run it first in the pipeline, ahead of the slower suites, so a wiring break fails the build in a minute and not after a long run.

Keep the test profile complete: every required property has a harmless value there, so a new required property forces a conscious edit to the test configuration.

Where this does not apply

If the context loads and a test fails, the problem is the test. If the error mentions an ApplicationContext in a non-Spring Boot project, check @ContextConfiguration and the XML or Java configuration location. The Spring Boot testing reference lists the slices and what each one loads, and the Spring TestContext framework reference explains caching.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.