Home > Software engineering >  How do I prevent Cucumber from running all @before code blocks even if the test is excluded from Tag
How do I prevent Cucumber from running all @before code blocks even if the test is excluded from Tag

Time:03-25

I'm having an issue where @Before blocks are being run, even if they are excluded from the Tag setting in the TestRunner file.

So when I run the testRunner file, it will start running the test I want with no issues, but at the same time, it will load a 2nd WebDriver window for the other test I dont want to run. This other test is only executing the @Before portion.

I have two cucumber feature files, with two step definition files. The feature files are in the "features" package while the stepdef files are in the "stepDefinition" package. Both stepdef files have an @Before code block that basically does my WebDriver setup and "getUrl" stuff.

Currently in my TestRunner file, I have it set to run only one tagged feature, and I tagged it appropriately in the corresponding feature file.

My problem is when I try to run my test, it still executes the @Before code in the other stepDef file.

The only way I found to prevent this is to put a "not @tagname" on the @Before code I dont want run. This is sort of cumbersome as I would have to do this for every single stepDef file I dont want to run.

Is there any other way to prevent @Before code from being run in tests you dont want run?

CodePudding user response:

Please be aware that Cucumber doesn't distinguish between different stepDefinition files; they are all considered the "glue". So just because you define one stepDefinition file for one feature, and another stepDefinition file for another feature (which btw is an anti-pattern), doesn't mean Cucumber sees these as separate.

Cucumber - by design - runs all hooks as defined; @Before hooks run before the first step of each scenario. If you want the hooks to be run only for certain features / scenarios, you will have to use Conditional Hooks, and tag your hooks with a tag expression:

From the docs on Conditional Hooks: "Hooks can be conditionally selected for execution based on the tags of the scenario. To run a particular hook only for certain scenarios, you can associate a Before or After hook with a tag expression.

Annotated method style:

@After("@browser and not @headless")
public void doSomethingAfter(Scenario scenario){
}

Lambda style:

After("@browser and not @headless", (Scenario scenario) -> {
});

"

For more information on tags, see tags

CodePudding user response:

I actually figured this out. I ended up creating a separate hooks class for the @Before/@After and removed them from the stepdefinition files. I then setup a dependency injection and made it so I could use the WebDriver instances in a more flexible way. Learned from this https://youtu.be/vxf1vq_da6E.

  • Related