Question

I want to specify certain setup and tear down steps for each specific feature file. I've seen hooks that allows code to execute before every scenario, and hooks to execute code before each feature, but I want to specify code to run once before and after all scenarios run for one specific feature.

Is this possible?

Was it helpful?

Solution

Do you use cucumber-jvm? I found an article that fits your requirement.

http://zsoltfabok.com/blog/2012/09/cucumber-jvm-hooks/

Basically, do not use JUnit @BeforeClass and @AfterClass for this, as they are unaware of Cucumber Hook Tags. You would want Init and Teardown methods to run for certain scenarios only right?

OTHER TIPS

It is if you are using junit to run your tests. We use the annotations to create a unit test class and a separate steps class. The standard @Before stuff goes in the steps class, but the @BeforeClass annotation can be used in the main unit test class:

@RunWith(Cucumber.class)
@Cucumber.Options(format = {"json", "<the report file"},
    features = {"<the feature file>"},
    strict = false,
    glue = {"<package with steps classes"})
public class SomeTestIT {
    @BeforeClass
    public static void setUp(){
       ...
    }

    @AfterClass
    public static void tearDown(){
       ...
    }
}

Try this :

In feature file :

@tagToIdentifyThatBeginAfterShouldRunForThisFeatureOnly
Feature : My new feature ....

In Stepdefinitions.java :

@Before("@tagToIdentifyThatBeginAfterShouldRunForThisFeatureOnly")
public void testStart() throws Throwable {
}

@After("@tagToIdentifyThatBeginAfterShouldRunForThisFeatureOnly")
public void testStart() throws Throwable {
}

Well I had the same requirement as yours. As per cucumber-jvm documentantion - Cucumber-JVM does not support running a hook only once.

So I followed null-check approach for a specific variable which is outcome of @Before in cucumber step hook. Something like below.

private String token;
public String getToken(){
     if (token == null) {
        token = CucumberClass.executeMethod();
      }
return token;
}

In above example let's suppose getToken() method gives you some token required before any scenario could run and you want token only once. This approach will execute your method only the first time i.e when it is null before any scenario starts executing. It significantly reduces the execution time also.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top