Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running background once for scenario outline examples in Cucumber Java

Tags:

java

cucumber

I want to run the background once for the below scenario so that while executing it, it should not go back the user to login screen again.

I found some replies where it says this is how cucumber works but could not find any alternative to do this.

What is the best way to handle this and how? if someone can share example code for this.

e.g.

Background:
    Given User logs into the application and on the home page

Scenario outline:
    When user fills the form "<FName>" and "<LName>"
    And click on submit button
    Then Result should display

    Examples:
    |FName|LName    | 
    |Abc | XYZ      |
    |Tom | Anderson |
like image 862
Lucky Avatar asked Jan 25 '18 17:01

Lucky


2 Answers

The best way to handle this is not to do it. There is a reason why Cucumber was designed this way. If you take this approach, and particularly if you use it widely, you will end up with a set of features that often break in really strange ways because of whats happened in previous scenarios. In your current example for instance if filling in the form does not take you back to the place where you can fill in the form, the second example will fail because you are not in the correct place.

like image 58
diabolist Avatar answered Sep 18 '22 12:09

diabolist


You will need to setup a static flag in the class containing the matching background step definition. Initially set it to false (or true if you prefer). Create a if condition in the step definition to check the value of the flag. Set it to the opposite value and place the desired action inside the if condition. This should execute only the first time.

private static boolean flag = false;

@Given("^User Logs In$")
public void userLogsIn() {
    if(flag==false) {
        flag=true;
        //Place the code you want to run only for first time
    }
}
like image 28
Grasshopper Avatar answered Sep 19 '22 12:09

Grasshopper