【问题标题】:why application context cannot be loaded?为什么无法加载应用程序上下文?
【发布时间】:2013-01-07 12:09:06
【问题描述】:

任何人都可以解释为什么我在测试我的测试用例时会收到以下错误消息“无法加载 ApplicationContext”

 mvn test

【问题讨论】:

  • 我们需要查看您的测试类和配置。
  • 阅读堆栈跟踪,你应该得到一个关于发生了什么的提示。它可能是 spring 在读取 appcontext xml 时遇到的任何问题,例如无效的 xml,或未找到的指定类,或在 bean 上指定的无效属性。

标签: spring-mvc maven-3 junit4


【解决方案1】:

如果您使用 Spring 框架,您可以使用 @ContextConfiguration 注解指定 applicationContext.xml 文件的位置:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/path/to/your/applicationContext.xml" })
public class MyTest {

}

【讨论】:

  • 即使配置 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/src/test/resources/applicationContext.xml" }) 我的问题没有解决
  • 同样的错误“application context.xml”无法加载
【解决方案2】:

检查您的@ContextConfiguration。引用自Spring documentation

普通或相对路径——例如“context.xml”——将被处理 作为类路径资源,相对于其中的包 定义了测试类。以斜杠开头的路径被视为 绝对类路径位置,例如“/org/example/config.xml”。一个 表示资源 URL 的路径(即前缀为 classpath:、file:、http: 等)将按原样使用。

所以我想你必须使用“/applicationContext.xml”而不是“/src/test/resources/applicationContext.xml”,因为文件将放置在类路径的根级别。

【讨论】:

    【解决方案3】:

    由于我看不到您的配置,您可以更改您的测试以使用以下类级别注释。这应该有助于找到应用程序上下文,只要它位于类路径中。

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({ "classpath:applicationContext.xml" })
    

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      相关资源
      最近更新 更多