Spring - @ContextConfiguration无法加载src/test/resources中的配置文件

26

我尝试使用以下抽象类在src/test/resources类路径中加载spring配置文件:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/applicationContext.xml"})
public class BaseIntegrationTests {

}

我在src/test/resources中有applicationContext.xml文件,但是Spring无法加载它。

谢谢。


1
请务必使用代码块来分隔代码片段。 - Josh K
2
我认为你不需要使用 /,只需使用 classpath:applicationContext.xml - ant
这符合我的需求:https://dev59.com/gmkv5IYBdhLWcg3wvDTq - user1026870
7个回答

26
要准确的说,它是在类路径下的测试输出目录(target/test-classes)的内容,而不是src/test/resources。但是,在默认情况下,通过resources:testResources目标(绑定到process-test-resources阶段)将src/test/resources下的资源复制到测试输出目录中。

话虽如此,您的代码看起来很好,并且测试源代码的资源应该已经被IDE或Maven复制并可用于类路径。那么一定是有其他问题。我看到你的类是集成测试的基类。你在pom.xml中配置了什么奇怪的东西吗?可以展示一下吗?


1
处理测试资源有所帮助。已修复pom文件。谢谢! - Azee
我的资源在测试类目录上,我可以使用 Myclass.class.getClassLoader.getResource("/my/path") 加载该文件。但是无法使用 @ContextConfiguration(location = "classpath:/my/path") - herau

16

尝试使用 * 以便它可以搜索到您的类路径

@ContextConfiguration(locations={"classpath*:applicationContext.xml"})

4
{"classpath:applicationContext.xml" 相比,* 通配符可以搜索类路径中的任意深度。我找不到解释这一点的文档。 - markdsievers
1
@markdsievers 它会将多个文件合并成一个,而不是选择找到的第一个文件。请参见:https://dev59.com/cnA75IYBdhLWcg3wdIl0#3294506 - Matthias

6

使用spring-test依赖(包括SpringJUnit4ClassRunner)与JUnit版本> 4.4存在已报告的错误

如果您使用的是新于4.4的JUnit版本,请尝试将其降级为4.4并查看是否解决了问题。


4

您的应用程序上下文必须包含在类路径中,并放置在 * 中:

@ContextConfiguration(locations = { "classpath:*/application-context.xml" })

2

您似乎正在使用Maven,并尝试在Eclipse中运行测试。请检查buil文件夹(target/test-classes/)是否有applicationContext.xml。如果没有,请先进行构建。


这对我来说也是如此。谢谢,它帮了我,节省了时间。 - SDB

0
如果您正在使用Maven并从Eclipse运行测试用例, 项目右键单击> Maven > maven update (ALTF5)可能适用于您。

0

我认为我有一个类似的问题,我发现我的application-context.xml文件既不在target/test-classes目录下,也不在src/test/resources目录下。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接