Julius
Julius

Reputation: 509

Cucumber hooks control flow?

I'm trying to write automated UI tests using Espresso and Cucumber. So far I've managed to successfully execute step definitions for a feature that tests a single activity using ActivityTestRule. I use Cucumber's @Before annotation to prepare for the scenario, for example launch the required activity. The issue is that when I try to execute a test suite containing more than one feature definition all @Before blocks will be called before every scenario. For example when the instrumentation core starts executing scenario 1, it executes the @Before methods both in scenario 1 and scenario 2 resulting in overlapping activity launches and failing tests.

public class Activity1Stepdefs {

    @Before
    public void setUp() {
        // Called before both scenario 1 and scenario 2, needs to be called only before scenario 1. 
    }

    @Given("^scenario 1$")
    public void scenario_1() throws Throwable {
        // Scenario 1
    }
}

public class Activity2Stepdefs {

    @Before
    public void setUp() {
        // Called before both scenario 1 and scenario 2, needs to be called only before scenario 2. 
    }

    @Given("^scenario 2$")
    public void scenario_2() throws Throwable {
        // Scenario 2
    }
}

Resulting control flow:

  1. Activity1Stepdefs.setUp()
  2. Activity2Stepdefs.setUp()
  3. Activity1Stepdefs.scenario_1()
  4. Activity2Stepdefs.setUp()
  5. Activity1Stepdefs.setUp()
  6. Activity2Stepdefs.scenario_2

Desired control flow:

  1. Activity1Stepdefs.setUp()
  2. Activity1Stepdefs.scenario_1()
  3. Activity2Stepdefs.setUp()
  4. Activity2Stepdefs.scenario_2

Upvotes: 0

Views: 373

Answers (1)

Murthi
Murthi

Reputation: 5347

This can be achieved by tagged hooks. First assign tags for scenario 1 and 2 in the feature file then create tagged hooks as give below. Assume I have given tag name for scenario 1 and 2 as scen1 and scen2 respectively. before ("@scen1") public void scenarioOneSetup() { // code for scenario 1 setup } before ("@scen2") public void scenarioTwoSetup() {// code for scenario 2 setup}

Upvotes: 1

Related Questions