0

目标:在课后将 2 级上下文配置标记为脏。

约束:第 2 级上下文必须与第 1 级上下文合并。


背景:

  • 我有多个使用common-context.xml.
    我将它们称为“普通”
  • 其中一些 IT 还使用另一个上下文X-context.xml
    我将它们称为“common + X”
  • 一些“common + X” IT需要同时加载common-context.xml 。我知道这需要糟糕的初始设计,但我目前面临一个巨大的系统,不可能进行如此剧烈的重构。X-context.xml

我试过的:

所有可能的组合:

  1. @ContextConfiguration
  2. @ContextHierarchy
  3. @DirtiesContext
  4. 名称变量。
  5. 继承位置变量。

样本:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations =  "classpath:/META-INF/common-context.xml" )
public abstract class AbstractIntegrationTest extends AbstractJUnit4SpringContextTests {

}

public class IT1 extends AbstractIntegrationTest {
    // Some tests...
}

@ContextHierarchy(  @ContextConfiguration(locations = "X-context.xml")  )
@DirtiesContext(classMode = ClassMode.AFTER_CLASS, hierarchyMode = HierarchyMode.CURRENT_LEVEL)
public class IT2 extends AbstractIntegrationTest {
    // Some tests...
}

public class IT3 extends AbstractIntegrationTest {
    // Some tests...
}

预期行为:

现在,如果测试碰巧按此顺序运行(IT1 --> IT2 --> IT3):

common-context.xml is up.
IT1 runs.

X-context.xml is up.
IT2 runs using common-context and X-context.
X-context.xml is down.

IT3 runs.
common-context.xml is down.

只要“X-context”不需要与“common-context”一起加载,这就可以正常工作。

根本问题:

为了同时加载“common”和“X”上下文,它们必须被合并。
否则,加载“common”,然后加载“X”。一些测试依赖于同时加载的两个上下文。

合并它们会禁用仅将第二级上下文标记为脏的选项。


为了合并它们,我们重构:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy(  @ContextConfiguration(name="common", locations="classpath:/META-INF/common-context.xml")  )
public abstract class AbstractIntegrationTest extends AbstractJUnit4SpringContextTests {

}

public class IT1 extends AbstractIntegrationTest {
    // Some tests...
}

@ContextHierarchy(  @ContextConfiguration(name="common", locations="X-context.xml", inheritLocations=false)  )
@DirtiesContext(classMode = ClassMode.AFTER_CLASS, hierarchyMode = HierarchyMode.CURRENT_LEVEL)
public class IT2 extends AbstractIntegrationTest {
    // Some tests...
}

public class IT3 extends AbstractIntegrationTest {
    // Some tests...
}

实际行为:

现在,如果测试碰巧按此顺序运行(IT1 --> IT2 --> IT3):

common-context.xml is up.
IT1 runs.

common-context.xml + X-context.xml is up.
IT2 runs.
common-context.xml + X-context.xml is down.

IT3 runs.
common-context.xml is down.

这样,我们就没有利用第一个出现的公共上下文。


可能的解决方案:

我认为可以解决问题但我不知道如何实现的一些想法:


我读过的:

4

0 回答 0