Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class})
@ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested


Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest


You can add to your application.yml in tests resources lazy-initialization:

spring:
  application:
    name: service
  main:
    allow-bean-definition-overriding: true
    lazy-initialization: true

Was able to fix the same issue with the annotation below. So in this case only the target class (Abc.class) is used by Spring, not the whole app context.

@SpringBootTest(properties = "spring.main.lazy-initialization=true",
classes = {Abc.class})