๐ด The Error You're Seeing
Confirm this matches your console output. If it does, you're in the right place.
2023-10-25 10:15:30.812 ERROR 12345 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource...โก Quick Fix Works 80% of the time
Use @AutoConfigureTestDatabase to replace your real DB with H2 during tests.
@SpringBootTest
@AutoConfigureTestDatabase
public class MyIntegrationTest { ... }๐ ๏ธ Solutions (3 Ways to Fix)
Use @AutoConfigureTestDatabase
๐ Use this when your test fails because it can't connect to your real database.
This annotation tells Spring Boot to replace your configured database with an in-memory H2 database for the duration of the test.
@SpringBootTest
@AutoConfigureTestDatabase
public class MyIntegrationTest { ... }Use Slice Tests (@WebMvcTest, @DataJpaTest)
๐ Use this when you only need to test a specific layer, not the whole context.
Slice tests load only the components needed for a specific layer (e.g., @WebMvcTest loads only Controllers). This is faster and avoids context loading issues.
@WebMvcTest(UserController.class)
public class UserControllerTest { ... }Create a test application-test.properties
๐ Use this when your test is picking up your production configuration.
Create a properties file specifically for tests that overrides database URLs and disables features not needed in tests.
# src/test/resources/application-test.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.hibernate.ddl-auto=create-drop๐ Version Notes
Standard behavior. Test context failures often masked underlying issues.
Stricter bean creation. Fails faster on missing beans or configuration issues.
๐ง Why this Happens
Tap to expand the deep technical explanation
When you run @SpringBootTest, Spring tries to boot the entire application context. If ANY bean fails to initialize (e.g., missing database, missing property, bean conflict), the context fails to load, and the test crashes.
The HITEC City Parking Spot Analogy:
It's like trying to start a car engine, but one of the spark plugs is missing. The engine (ApplicationContext) won't start until all parts (beans) are present and working.
๐ก๏ธ How to Prevent This Next Time
Use slice tests (@WebMvcTest, @DataJpaTest) instead of @SpringBootTest whenever possible to minimize context loading issues.