Failed to load ApplicationContext for JUnit test of Spring controller
As mentioned in the discussion: WEB-INF
is not really part of the class path. If you use a common template, such as maven, use src/main/resources
or src/test/resources
to place the app-context.xml
in. Then you can use classpath:
.
Place your config file in src/main/resources/app-context.xml
and use the following code:
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:app-context.xml")public class PersonControllerTest { ...}
You can also create your test context with different configurations of beans.
Place your config file into src/test/resources/test-app-context.xml
and use:
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:test-app-context.xml")public class PersonControllerTest { ...}
There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class)
at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.
An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest
combined with @AutoConfigureMockMvc
rather than @WebMvcTest
If you are using Maven, add the below config in your pom.xml:
<build> <testResources> <testResource> <directory>src/main/webapp</directory> </testResource> </testResources></build>
With this config, you will be able to access xml files in WEB-INF folder.From Maven POM Reference:The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.