【问题标题】:Testing with Spring and Maven: applicationContext使用 Spring 和 Maven 进行测试:applicationContext
【发布时间】:2012-04-23 15:58:25
【问题描述】:

这个问题似乎很古老,但我仍然找不到解决方案..

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml", "/PersonsPopulateTest-context.xml"})
@Transactional
public class PersonsPopulateTest {

文件位于:

src
   main
      resources
           applicationContext.xml

src        
   test
      resources
          PersonsPopulateTest-context.xml 

因此,在构建这些文件后,这些文件位于 target/classestarget/test-classes

但是 mvn test 命令仍然显示:Failed to load ApplicationContext

官方文档怎么说:

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"
// in the root of the classpath
@ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"})
public class MyTest {
    // class body...
}

我哪里做错了?

谢谢, 弗莱基米尔

更新。万无一失的报告:

java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.IllegalArgumentException: Can not load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration.
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:117)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
... 30 more

【问题讨论】:

  • 你能用stacktrace显示准确的错误信息吗?
  • 我认为applicationContext.xml 必须位于您的src/test/resources 中。 AFAIK 测试无法访问 src/main 文件夹。
  • @Maroe:不,测试可以访问主类路径。如果不能,他们如何加载被测类?
  • 我在 src/test/resources 中也添加了 applicationContext.xml,它出现在 target/test-classes 中,但测试仍然失败并出现同样的错误
  • 只需这样做 classpath:applicationContext.xml 而不是 /applicationContext.xml 你的问题应该会消失,这将加载应用程序上下文因为它在运行时类路径中,在这种情况下,将 applicationContext.xml 放在 src/test/resourcessrc/main/resources 应该可以工作

标签: spring unit-testing maven


【解决方案1】:

我认为 Maven 根本没有包含来自 main/resources 的 XML 文件。

您可以尝试明确指定要在 pom.xml 中包含的内容。

如果以下配置有效,请告诉我:

    <!-- Add this directly after the <build>-opening tag -->
    <resources>
        <resource>
            <filtering>true</filtering>
            <directory>src/test/resources</directory>
            <includes>
                <include>**/*.properties</include>
            </includes>
            <excludes>
                <exclude>**/*local.properties</exclude>
            </excludes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>

这是我在你的情况下使用的东西。如果您没有要包含的属性文件,您可以对其进行编辑。

【讨论】:

  • Maven 默认包含来自src/test/resourcessrc/main/resources 的所有内容。您可以在package 之后轻松检查目标中的这些文件。所以显然问题不在这个。我想 Prasanna Talakanti 在评论中指出的上下文声明是错误的。
【解决方案2】:

我的测试上下文文件位于 src\test\resources\spring 文件夹下。 我设法用

加载上下文
@ContextConfiguration(locations={"classpath:**/test-context.xml"})

但对 src\main\resources\spring 文件夹下的 application-context.xml 的引用(在 test-context.xml 中)失败

我设法通过在测试类中创建 ClassPathXmlApplicationContext 来加载应用程序上下文

ClassPathXmlApplicationContext appContext=new ClassPathXmlApplicationContext(new String[]{"classpath:spring/application-context.xml","classpath:spring/model-context.xml"});

让我知道这是否有帮助或可能会产生任何其他问题。

【讨论】:

  • 我设法用 引用了 test-context.xml 中的 application-context.xml
【解决方案3】:
<!-- Add this directly after the <build>-opening tag in the your pom-->
            <testResources>
                <testResource>
                    <directory>src/test/resources</directory>
                    <filtering>true</filtering>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </testResource>
            </testResources>

【讨论】:

    【解决方案4】:

    我遇到了同样的问题,所有文件都成功复制到target/classestarget/test-classes,仍然spring不能找到他们。

    当我在 pom

    中明确指定 ma​​ven-surefire-pluginma​​ven-resources-plugin 的版本时,问题消失了

    【讨论】:

    • 你设置了什么版本?我尝试设置这个插件的所有版本,但它仍然不起作用
    【解决方案5】:

    更新: 实际上,在我的情况下,问题在于启用了Compile on Save 选项。我使用 Netbeans,选项设置为For test execution only。此值编译更改的文件并用新文件替换资源。但是,由于除了测试资源之外还使用了应用程序资源,For test execution onlytarget 文件夹中生成了错误生成的资源。

    更改Compile on Save=For test execution only

    Compile on Save=Disable 解决问题。

    下面的文字也是正确的,但有时不起作用。直到我重新启动 Netbeans IDE 才有效。但是,问题原因的详细信息是正确的,因此我宁愿离开测试。


    旧: 在我的情况下,我在src/main/resources 中有appContext-test.xml。 当我更改任何代码并启动一个单元测试(不是全部)时,它会重新编译并正确执行。但是,如果我再次启动相同的单元测试,它会因java.lang.IllegalStateException: Failed to load ApplicationContext 而失败。

    我已将pom.xml 更改为

    <build>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/java/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
    </build>
    

    <build>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/main/resources</directory>
                <filtering>true</filtering>
            </testResource>
            <testResource>
                <directory>${project.basedir}/src/test/java/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
    </build>
    

    现在一切正常。

    错误是由于appContext-test.xml 使用了带有很多变量的src/main/resources/my.properties 文件

    database.url = ${database.url}
    database.username = ${database.username}
    database.password = ${database.password}
    

    在构建期间填充。但是,如果您在testResource 中跳过src/main/resources,则my.properties 将按原样添加到target/classes/my.properties,例如没有替代。这个文件当然打破了上下文。

    PS:您可以删除 ${project.basedir}/ - 这是我的自定义设置。

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

      • 找到您的 xml 的最佳方式
      【解决方案7】:

      我认为最佳实践是将用于测试 PersonsPopulateTest-context.xml 的应用程序上下文文件放在 src/test/resources 下。该文件将被复制到 target/test-classes 中,您可以在测试类中引用它,如下所示:

      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(locations = {"classpath:**/PersonsPopulateTest-context.xml"})
      @Transactional
      public class PersonsPopulateTest {
      
      }
      

      如果你还想引用 src/main/resources 下的 applicationContext.xml,那么你必须将它包含如下:

      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(locations = {"file:src/main/resources/applicationContext.xml"})
      @Transactional
      public class PersonsPopulateTest {
      
      }
      

      它对我有用。

      【讨论】:

        【解决方案8】:

        由于某种原因,我遇到了同样的问题,当我使用 JDK6 而不是 JDK8 运行 maven 测试时它工作正常(在我的情况下,这是一个遗留应用程序)

        如果它对任何人有帮助。

        【讨论】:

          【解决方案9】:

          我遇到了同样的问题。对我来说,测试通过 eclipse 成功运行。但是,当我运行 mvn test 时,它给了我错误:Failed to load ApplicationContext

          修复:将 src/test/resources 目录添加到 surefire 的类路径 插件作为-

          <plugin>
                      <groupId>org.apache.maven.plugins</groupId>
                      <artifactId>maven-surefire-plugin</artifactId>
                      <version>2.10</version>
                      <configuration>
                          <additionalClasspathElements>
                              <additionalClasspathElement>${project.basedir}/src/test/resources</additionalClasspathElement>
                          </additionalClasspathElements>      
                      </configuration>
          

          Adding classpath to SureFire

          希望对你有帮助。

          【讨论】:

            【解决方案10】:

            在您的集成测试类中,尝试添加

            @Test
            public void contextLoads(){
            }
            

            【讨论】:

              猜你喜欢
              • 2012-12-08
              • 2014-11-21
              • 1970-01-01
              • 2021-10-22
              • 2014-05-28
              • 1970-01-01
              • 2019-04-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多