由 Cucumber 执行的集成测试往往会留下导致后续测试出现问题的上下文。明显的解决方案似乎是 Spring 的 @DirtiesContext
,但它不是在运行所有 cucumber 功能之后拆除上下文,而是在每个场景之后都这样做,从而使测试执行时间相当长。
也尝试使用 @TestExecutionListeners
,但没有成功。
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( classes = { MyApplication.class, MyTestComponent.class }, loader = SpringApplicationContextLoader.class )
@ActiveProfiles( { "test", "someotherprofile" } )
@DirtiesContext( classMode = DirtiesContext.ClassMode.AFTER_CLASS )
@WebIntegrationTest( randomPort = true )
public class StepDefs extends StepDefUtils {
// givens, whens, thens
我是否尝试以不受支持的方式使用 DirtiesContext?
最佳答案
正如之前的回答所说,场景被编译并作为单独的类运行,阻止 DirtiesContext 工作,并且出于同样的原因, cucumber 中没有每个功能 Hook 。
解决方法是将标签放在场景中,让一个带钩子(Hook)的类检测这些标签,并在 afterTestClass 方法期间有条件地弄脏上下文。 标签让您可以控制上下文何时变脏,例如,如果希望每个功能都有新鲜的上下文,然后用标签标记最后一个场景,或者每个功能可以在需要时有很多时间。
public class CucumberFeatureDirtyContextTestExecutionListener extends AbstractTestExecutionListener{
private static boolean dirtyContext = false;
@After("@DirtyContextAfter")
public void afterDirtyContext(){
dirtyContext = true;
}
@Override public void afterTestClass(TestContext testContext) throws Exception {
if (dirtyContext) {
testContext.markApplicationContextDirty(HierarchyMode.EXHAUSTIVE);
testContext.setAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, TRUE);
dirtyContext = false;
}
}
}
用标签标记场景
@DirtyContextAfter
Scenario: My scenario
在steps类中向spring注册监听器
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class, CucumberFeatureDirtyContextTestExecutionListener.class})
确保监听器在 cucumber 胶中,以便在注册钩子(Hook)之后
无法在 beforeClass 上运行,因为上下文已经设置,所以必须在 afterClass 上运行。
关于java - @DirtiesContext 在每个 cucumber 测试场景之后撕下上下文,而不是类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37863502/