Skip to content
Latchkey

Spring Test "Failed to load ApplicationContext" in CI - Fix the Context

Failed to load ApplicationContext is the umbrella Spring test failure: the test's context could not be built. The real reason is the nested Caused by - a bean that could not be created, a missing property, or a datasource that could not connect.

What this error means

A @SpringBootTest / @DataJpaTest fails in setup with java.lang.IllegalStateException: Failed to load ApplicationContext, then a Caused by: (BeanCreationException, missing property, connection refused). All tests in the class error out the same way.

junit
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration ...]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'orderService' ...
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'app.api.key'

Common causes

A bean or property failed in the test profile

A required property absent in CI, a wrong test profile, or a bean dependency that cannot be satisfied stops the whole context from loading.

A real resource is required by the context

A datasource/broker the context wires eagerly cannot connect in CI (no DB, no Docker), so context startup fails. (See the Testcontainers/DB pages for that infra case.)

How to fix it

Read the nested cause and supply what is missing

Provide the missing property or profile, or slice the context to only what the test needs.

.github/workflows/ci.yml
# Provide test properties / activate a profile in CI
- run: mvn -B test -Dspring.profiles.active=test -Dapp.api.key=ci-dummy

Narrow the context with a test slice

  1. Use @WebMvcTest/@DataJpaTest slices instead of full @SpringBootTest when you do not need the whole app.
  2. Add a src/test/resources/application-test.yml with safe defaults for required properties.
  3. For external resources, mock the bean (@MockBean) or use Testcontainers rather than a real service.

How to prevent it

  • Keep a dedicated test profile with all required properties, prefer Spring test slices, and mock or containerize external dependencies so the context always loads in CI.

Frequently asked questions

What causes ""IllegalStateException: Failed to load ApplicationContext""?
A required property absent in CI, a wrong test profile, or a bean dependency that cannot be satisfied stops the whole context from loading.
How do I fix "IllegalStateException: Failed to load ApplicationContext"?
Provide the missing property or profile, or slice the context to only what the test needs.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card