【问题标题】:Cannot process locations AND classes for context configuration无法处理上下文配置的位置和类
【发布时间】:2015-03-14 19:24:16
【问题描述】:

我写了以下测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:META-INF/dataContext.xml"},classes = Configiuration.class)
@ActiveProfiles("test")
public class CityDaoImplTest {
....
}

当我调用时,我需要使用来自 xml 文件和 java 类 bur 的配置

mvn 测试我在控制台中看到以下内容:

Tests in error: 
  initializationError(***.CityDaoImplTest): Cannot process locations AND classes for context configuration [ContextConfigurationAttributes@5bb21b69 declaringClass = '***.CityDaoImplTest', classes = '{***.Configiuration}', locations = '{classpath:META-INF/dataContext.xml}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader']; configure one or the other, but not both.

如何在不重写配置的情况下修复它?

【问题讨论】:

    标签: java testing junit configuration spring-test


    【解决方案1】:

    即使你迟到了,我也会发布我的答案,只是为了帮助其他阅读这篇文章的人。

    另一种解决方案是在 dataContext.xml 中将您的配置类声明为 bean。

    您需要做的就是:

    <bean class="com.packageWhereConfigClassIsPresent.Configuration"/>
    

    希望对某人有所帮助;)

    【讨论】:

      【解决方案2】:

      来自Spring Docs

      在 Spring 3.1 之前,仅支持基于路径的资源位置。从 Spring 3.1 开始,上下文加载器可以选择支持 either 基于路径的 基于类的资源。从 Spring 4.0.4 开始,上下文加载器可以选择同时支持基于路径的类资源。

      但是,使用 spring-test 有一个小警告。它使用基于AbstractDelegatingSmartContextLoaderSmartContextLoader,不幸的是它不是那么聪明;)

      @Override
      public void processContextConfiguration(
              final ContextConfigurationAttributes configAttributes) {
      
          Assert.notNull(configAttributes, "configAttributes must not be null");
          Assert.isTrue(!(configAttributes.hasLocations() && configAttributes.hasClasses()), String.format(
              "Cannot process locations AND classes for context "
                      + "configuration %s; configure one or the other, but not both.", configAttributes));
      

      如代码所示,位置和类不能同时设置。

      那么,如何解决这个问题?好吧,一种解决方案是添加一个额外的配置类,如下所示:

      @Configuration
      @ImportResource("classpath:META-INF/dataContext.xml")
      class TestConfig {
      
      }
      

      并且,在您的测试代码中使用以下内容:

      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(classes = {Configuration.class, TestConfig.class})
      @ActiveProfiles("test")
      public class CityDaoImplTest { ... }
      

      从技术上讲,这是重写配置,但您不必更改现有配置,只需添加一个新的 @Configuration 类(该类甚至可以与您的测试在同一个文件中案例)。

      【讨论】:

      • 来自我的 pom:4.0.7.RELEASE
      猜你喜欢
      • 2014-05-15
      • 2017-01-15
      • 2011-11-16
      • 2018-08-26
      • 2019-09-11
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多