问题
I'm trying to figure out how to run some code before and after all my cucumber tests run.
I've been tracking down a bug for a few days where some our processes create jobs on a server, and don't properly clean it up. It's easy to miss so ideally I don't want engineers to have to manually add a check to every test.
I was hoping there'd be a way to put a hook in before any tests ran to cache how many jobs exist on the server, then a hook at the end to ensure that the value hasn't changed.
I know this isn't really the best way to use cucumber, as that is more of a system test type thing to do, but doing it this way would be the best way to fit it into the existing infrastructure.
回答1:
How about using tagged hooks.
@Before("@jobCheck")
public void beforeScenario() {
// actions
}
@After("@jobCheck")
public void afterScenario() {
// actions
}
And then for each scenario that requires this check, add @jobCheck before the Scenario definition as below.
Feature: Some feature description
@jobCheck
Scenario: It should process a sentence
// The steps
More on JVM hooks here: https://zsoltfabok.com/blog/2012/09/cucumber-jvm-hooks/
回答2:
Use @BeforeClass and @AfterClass annotations in your run file.
@RunWith(Cucumber.class)
@Cucumber.Options(
format = {"json", "<the report file>"},
features = {"<the feature file>"},
strict = false,
glue = {"<package with steps classes>"})
public class TestRunFile {
@BeforeClass
public static void getJobNumbersOnServerBeforeStarting() {
//Implement logic
}
@AfterClass
public static void getJobNumbersOnServerAfterCompletion() {
//Implement logic
}
}
来源:https://stackoverflow.com/questions/51192858/how-to-run-code-before-after-cucumber-suite