Search code examples
mavenseleniumcucumbercucumber-javacucumber-junit

Tagged hooks are running for every test


My Hooks class like below :

@Before("@Firefox")
public void setUpFirefox() {}

@Before("@Chrome")
public void setUpChrome() {}

@After
public void tearDown(){}

When I run the following command mvn test -Dcucumber.options="--tags @Chrome" both @Before functions are calling.

How can I run specific @Before method depending on maven command?

My Runner class (I already tried with tags option, it is also not working for me) :

@RunWith(Cucumber.class)
@CucumberOptions(
        plugin = {"pretty", "json:target/cucumber-reports/Cucumber.json",
                "junit:target/cucumber-reports/Cucumber.xml",
                "html:target/cucumber-reports"},
        features = {"src/test/features/"},
        glue = {"steps"})


public class RunCukesTest {
}

My feature file :

Feature: Storybook
  @Test @Widgets @Smoke @Chrome @Firefox
  Scenario: Storybook example
    Given The user clicks on "storybook" index on the homepage
    And Storybook HomePage should be displayed

Solution

  • It looks like it's because you've got both tags for that scenario, the before hooks seem to execute based on the scenario that's running. e.g.

    -The tag command line --tags @Chrome etc. specifies which scenario to run

    -Now based on that scenario, execute the before functions with the tags attached to that scenario (Test, Widgets, Smoke, Chrome, Firefox)

    If you were to have a Before hook for the tag Smoke, I would imagine that would also run.

    For example:

    (It's in Scala)

    Before("@test1") { _ =>
        println("test1 before actioned")
      }
    
      Before("@test2") { _ =>
        println("test2 before actioned")
      }
    

    With the feature file:

    [...]
      @test1
      Scenario: Test scenario 1
        Given Some precondition occurs
    
      @test2
      Scenario: Test scenario 2
        Given Some precondition occurs
    
    

    When I run either of those tags, I get the output

    test1 before actioned or test2 before actioned

    However, have both tags on one scenario then both lines are printed.

    What's being actioned in those setupChome, setupFirefox functions, just setting the driver up? You could create new system property such as browser for example, match on the value and execute some setup then you could type in:

    -Dbrowser=chrome and it would do the setup that way.