当包含@Nested类时,是否可以将@DirtiesContext指定为只在整个主测试类之后变脏



似乎没有办法指定@DirtiesContext来避免在每个@Nested类之后重新加载上下文。

我找到了一种通过编程避免这种情况的方法,但是,最好有一个注释参数来实现这一点,避免需要自定义侦听器,因为它会使默认侦听器无效。

提到的自定义侦听器

/**
* Disallow context dirtying for nested classes
*/
public static final class TestDirtiesContextTestExecutionListener extends DirtiesContextTestExecutionListener {
@Override
protected void beforeOrAfterTestClass(TestContext testContext, DirtiesContext.ClassMode requiredClassMode) throws Exception {
if ( ! testContext.getTestClass().getName().contains("$")) {
super.beforeOrAfterTestClass(testContext, requiredClassMode);
}
}
}

您可以尝试在顶级上设置以下注释:

@NestedTestConfiguration(NestedTestConfiguration.EnclosingConfiguration.OVERRIDE)

它将使这个(和其他注释(需要重写而不是继承(自springframework5.3以来的默认值(可在弹簧测试文件中找到有关嵌套测试的其他信息

最新更新