Fails to load Spring application context in tests with SpringJUnit4ClassRunner

試著忘記壹切 提交于 2019-11-29 12:43:49

This will work.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:**/webapp/WEB-INF/springMVC-config/mainController-servlet.xml")
public class DiagnosticsControllerTest {
...
}

Aside from not being able to reference the correct path to your XML configuration file, the truth is:

You are not even using the Spring TestContext Framework in the example you provided.

Rather, you are only using Mockito and Spring MVC Test (i.e., MockMvc).

Thus, you can simply delete the @RunWith and @ContextConfiguration declarations completely.

ipsi

src/main/webapp is not on the classpath, hence it can't find the file.

See Spring @ContextConfiguration how to put the right location for the xml for an explanation of why it's bad to put Spring configuration into webapp.

The solution would be to move your configuration into src/main/resources, and tweak however you're loading the Spring config files to look on the classpath for them. If you're using a web.xml file, that should be as simple as prefixing them with classpath:.

There are other solutions, but I feel that's the best option in the long-term.

David B

In order for me to get rid of the error "Failed to load applicationContext", I had to upgrade Spring to 4.3.6.RELEASE and JUnit to 4.12. This error happened to me when trying to run a JUnit test with Java 1.8 after I had introduced lambdas, even though the file was located in src/main/resources.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!