In my feature files I have scenario and scenario outlines in gherkin. I would like to get those descriptions within the tests that they define. For example
Scenario: Create a customer
or
Scenario Outline: Create a customer that has <item> items (item fed by a table)
I want to use the description above in the test it defines for ease of knowing what test put what user into the database. Is there a way to get this description from within the test?
A
You can use hooks (see https://www.baeldung.com/java-cucumber-hooks)
@Before
public void beforeScenario(Scenario scenario) {
System.out.println("Before scenario " + scenario.getName());
}
If you want to share this between steps, and you are using cucumber-spring, you may want to use the cucumber-glue
scope.
public class MyContext {
private Scenario scenario;
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public Scenario getScenario() {
if (this.scenario == null) {
throw new RuntimeException("Scenario has not been set");
}
return this.scenario;
}
}
@Configuration
public class MyConfiguration {
@Bean @Scope("cucumber-glue")
public MyContext myContext() {
return new MyContext();
}
}
public class MySteps1 {
@Autowired
private MyContext myContext;
@Before
public void beforeScenario(Scenario scenario) {
myContext.setScenario(scenario);
}
@When(...)
public void whenX() { ... }
}
public class MySteps2 {
@Autowired
private MyContext myContext;
@When("something happens")
public void whenSomethingHappens() {
System.out.println("About to do something for " + scenario.getName());
}
}