Cucumber scenario outline and examples with generic step definitions

trial999 picture trial999 · Mar 25, 2014 · Viewed 53.3k times · Source

I have a Feature file which is as below:

Scenario Outline: Create ABC

  Given I open the application

  When I enter username as <username>

  And I enter password as <password>

  Then I enter title as <title>

  And press submit


Examples:

| username | password | title |

| Rob      | xyz1      | title1 |

| Bob      | xyz1      | title2 |

This mandates me to have step definitions for each of these values. Can i instead have a

generic step definition that can be mapped for every username or password or title values in

the examples section.

i.e instead of saying

@When("^I enter username as Rob$")
public void I_enter_username_as_Rob() throws Throwable {
    // Express the Regexp above with the code you wish you had
    throw new PendingException();
}

can i enter

@When("^I enter username as <username>$")
public void I_enter_username_as_username(<something to use the value passed>) throws Throwable {
    // Express the Regexp above with the code you wish you had
    throw new PendingException();
}

Answer

Bala picture Bala · Mar 26, 2014

You should use this format

Scenario Outline: Create ABC

    Given I open the application
    When I enter username as "<username>"
    And I enter password as "<password>"
    Then I enter title as "<title>"
    And press submit

Which would produce

@When("^I enter username as \"([^\"]*)\"$")
public void I_enter_username_as(String arg1) throws Throwable {
    // Express the Regexp above with the code you wish you had
    throw new PendingException();
}

arg1 will now have your username/value passed.