无法处理上下文配置的位置和类

gst*_*low 16 java testing configuration junit spring-test

我写过以下测试:

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

我需要在调用时使用xml文件和java类bur中的配置

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

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.
Run Code Online (Sandbox Code Playgroud)

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

was*_*ren 43

来自Spring Docs:

在Spring 3.1之前,仅支持基于路径的资源位置.在Spring 3.1中,背景装载机可以选择支持任何基于路径基于类的资源.在Spring 4.0.4中,上下文装载机可以选择支持基于路径同时基于类的资源.

然而,通过弹簧测试,有一个小警告.它使用的SmartContextLoader是基于AbstractDelegatingSmartContextLoader,不幸的是它不那么聪明;)

@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));
Run Code Online (Sandbox Code Playgroud)

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

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


Adi*_*tzu 5

即使对你来说已经太晚了,我也会发布我的答案只是为了帮助其他会读到这篇文章的人。

另一个解决方案是在 dataContext.xml 中将 Configuration 类声明为 bean。

您需要做的就是:

<bean class="com.packageWhereConfigClassIsPresent.Configuration"/>
Run Code Online (Sandbox Code Playgroud)

希望它能帮助别人;)