Reuse Cucumber steps

前端 未结 5 1806
攒了一身酷
攒了一身酷 2020-11-28 19:44

I want to reuse some Cucumber steps but can\'t seem to find the right way.

I want to write a step like:

Given /^I login with (.*) credentials$/ |type         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 20:03

    Reuse keywords in feature file which will provide code reusability.

    It is highly NOT recommended to call step defs within step defs.

    I would write my feature file this way,

    Scenario Outline: To check login functionality
        Given I login with "" and ""
        Then I "" login successfully
    
    Examples:
        |username|password|may or may not|
        |paul    |123$    |may           |
        |dave    |1111    |may not       |
    

    In my step definition, (This is Java)

    @Given(I login with \"([^\"]*)\" and \"([^\"]*)\"$)
    public void I_login_with_and(String username, String password){
    
       //login with username and password
    
    }
    
    @Then(I \"([^\"]*)\" login successfully$)
    public void I_login_successully_if(String validity){
    
        if(validity.equals("may")){
            //assert for valid login
        }
        else
        if(validity.equals("may not")){
            //assert for invalid login
        }
    }
    

    In this way, there is a lot of code reusability. Your same Given and Then handles both valid and invalid scenarios. At the same time, your feature file makes sense to the readers.

提交回复
热议问题