Running background once for scenario outline examp

2019-07-03 15:13发布

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 |

标签: java cucumber
2条回答
Juvenile、少年°
2楼-- · 2019-07-03 15:30

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
    }
}
查看更多
贼婆χ
3楼-- · 2019-07-03 15:47

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.

查看更多
登录 后发表回答