【问题标题】:spring - @ContextConfiguration fail to load config file in src/test/resourcesspring - @ContextConfiguration 无法在 src/test/resources 中加载配置文件
【发布时间】:2011-02-05 23:41:10
【问题描述】:

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

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

}

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

谢谢。

【问题讨论】:

标签: java spring maven-2 junit junit4


【解决方案1】:

您似乎正在使用 Maven,并试图从 Eclipse 中运行测试。检查 applicationContext.xml 的构建文件夹 (target/test-classes/)。如果不存在,则必须先构建。

【讨论】:

  • 对我来说就是这种情况。谢谢它帮助并节省了我的时间
【解决方案2】:

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

话虽如此,您的代码看起来不错,并且测试源代码的资源应该在运行测试时由您的 IDE 或 Maven 复制,因此应该在类路径中可用。所以肯定有其他问题。我可以看到您的类是集成测试的基类。你有没有在你的 pom 中配置任何花哨的东西?可以展示一下吗?

【讨论】:

  • 过程测试资源帮助。修复了pom。谢谢!
  • 我的资源位于 test-classes 目录中,我可以使用Myclass.class.getClassLoader.getResource("/my/path") 加载文件。但不适用于@ContextConfiguration(location = "classpath:/my/path")
【解决方案3】:

有一个 reported bug 使用带有 JUnit > 4.4 版本的 spring-test 依赖项(包括 SpringJUnit4ClassRunner)。

如果您使用的 JUnit 版本高于 4.4,请尝试将其移至 4.4 并查看它是否能解决您的问题。

【讨论】:

    【解决方案4】:

    我想我有一个类似的问题, 我发现我的 application-context.xml 不在 src/test/resources 上的 target/test-classes/neighter

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

      • {"classpath:applicationContext.xml" 相比,* 做了什么?搜索类路径的任何深度?我找不到解释这一点的文档。
      • @markdsievers 它将多个文件合并为一个,而不是选择找到的第一个文件。见:stackoverflow.com/a/3294506/344480
      【解决方案6】:

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

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

      【讨论】:

        【解决方案7】:

        如果您使用 Maven 并从 eclipse 运行测试用例, 项目右键单击 > Maven > maven update (ALTF5) 可能对你有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-03-22
          • 2013-09-04
          • 2019-08-04
          • 1970-01-01
          • 2014-09-21
          • 1970-01-01
          • 1970-01-01
          • 2015-12-12
          相关资源
          最近更新 更多