java JUnit 错误:“无法加载 ApplicationContext”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44764218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:19:52  来源:igfitidea点击:

JUnit Error: "Failed to load ApplicationContext"

javamavenspring-mvcjunit4applicationcontext

提问by Amd046

Nothing seems to work

似乎没有任何效果

I'm trying to run simple test:

我正在尝试运行简单的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
@Transactional
public class EmailServiceTest {

I've also tried:

我也试过:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"src/main/webapp/WEB-INF/applicationContext.xml"})
@Transactional
public class EmailServiceTest {

Along with a few different things in place of "location," such as "classpath" and "file."

除了“位置”之外,还有一些不同的东西,例如“类路径”和“文件”。

The "ApplicationContext" is located:

“ApplicationContext”位于:

src
    main
        webapp
            WEB-INF
                applicationContext.xml

But JUnit test still says: Failed to load ApplicationContext

但是 JUnit 测试仍然说:无法加载 ApplicationContext

回答by Amd046

The issue was solved after we realized our build file was missing information pertaining to testing. Information such as the "app.properties" and " applicationContext" were not being copied into the testing resources. So technically, none of these were on the classpath.

在我们意识到我们的构建文件缺少与测试有关的信息后,问题得到了解决。“app.properties”和“applicationContext”等信息没有被复制到测试资源中。所以从技术上讲,这些都不在类路径上。

回答by Anshul Sharma

you need to use @ContextConfiguration(locations = { "file:./src/main/resources/ApplicationContext.xml" })after @RunWith(SpringJUnit4ClassRunner.class). and test.java file create at /src/test/java/your-package-name.

您需要@ContextConfiguration(locations = { "file:./src/main/resources/ApplicationContext.xml" })@RunWith(SpringJUnit4ClassRunner.class). 和 test.java 文件在/src/test/java/your-package-name.

回答by vhula

You have to specify an application context location on the classpath. src/mainis added to the classpath. Therefore, you need to specify only webapp/WEB-INF/applicationContext.xmlas follows: @ContextConfiguration(locations = {"webapp/WEB-INF/applicationContext.xml"}).

您必须在类路径上指定应用程序上下文位置。src/main被添加到类路径中。因此,您只需指定webapp/WEB-INF/applicationContext.xml如下:@ContextConfiguration(locations = {"webapp/WEB-INF/applicationContext.xml"}).