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.
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.
# Provide test properties / activate a profile in CI
- run: mvn -B test -Dspring.profiles.active=test -Dapp.api.key=ci-dummyNarrow the context with a test slice
- Use
@WebMvcTest/@DataJpaTestslices instead of full@SpringBootTestwhen you do not need the whole app. - Add a
src/test/resources/application-test.ymlwith safe defaults for required properties. - 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.