Search code examples
javacucumberappiumgherkin

Cucumber step definition class after hook executes even if step definition class not used?


So I have a pretty basic project using Appium/Cucumber/Gherkin in Java with JUnit. I originally wanted to use @Before and @After tags in each of my StepDefinition classes to create the driver and quit the driver and submit a report. The problem i'm running into is that even if none of my steps exist inside the step definition class, the class itself is still created which causes my @Before and @After tags to run.

I have a workaround for the initialization by basically moving my driver creation to a background step. But I haven't been able to figure out a way to properly use my driver quit and report functionality. I'm pretty sure I could do the same for my after case if I forced the functionality into the last step in each of my scenarios, but I was hoping for a cleaner more global approach.

Is this working as intended? or should the Step Definition classes only be instantiated when one of their functions is actually used? Have you run into this before?


Solution

  • Hooks in cucumber are global in nature. That is if the hook methods are coded in any class defined in the package structure given to the glue option of CucumberOption they will be executed.

    The way out is to use tags as filters in the Before and After hooks. And also you can fix up the order of execution of these tags.

    If you want a scenario to open browser in Before hook, give the scenario a @Browser tag. And in the @Before annotation use it like @Before("@Browser"). This will only run for scenarios with the Browser tag. Same goes for After hook.

    You can add the order attribute to Before and After tags to give precedence. @Before(value="@Browser", order=5). This will run before a Before hook method with order of say 10. For After hook order of 10 will run before one with 5.