问题
Integration test executed by cucumber tends to leave behind context that causes problems with subsequent tests. Obvious solution appeared to be Spring's @DirtiesContext
, but instead of tearing down the context after all the cucumber features have been run, it does this after each and every scenario, thus making the test execution time rather lengthy.
Tried also with @TestExecutionListeners
, but no luck.
@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
Am I trying to use DirtiesContext in an unsupported way?
回答1:
Cucumber test methods are compiled into different test classes so @DirtiesContext( classMode = DirtiesContext.ClassMode.AFTER_CLASS )
will be run after each test method.
Unfortunately I don't see any DirtiesContext mode which suits your needs. I would search for some cucumber listener and manually make spring context dirty trough it.
回答2:
As previous answer said the scenarios get compiled and run as separate classes stopping DirtiesContext from working and there are no per feature hooks in cucumber for same reason.
Workaround is to put tags in scenarios and have a class with hook detect these and conditionally dirty the context during the afterTestClass method. The tag lets you control when context gets dirtied for example if want each feature to have fresh context then mark last scenario with tag, or can have many time per feature as and when needed.
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;
}
}
}
Mark scenarios with tag
@DirtyContextAfter
Scenario: My scenario
On steps class register the listener with spring
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class, CucumberFeatureDirtyContextTestExecutionListener.class})
Make sure the listener is in cucumber glue so after hook is registerd
Could not get it working on beforeClass as the context is already set up so have to do on afterClass.
来源:https://stackoverflow.com/questions/37863502/dirtiescontext-tears-context-down-after-every-cucumber-test-scenario-not-class