Reusable/Generic Examples table in Cucumber

2019-05-22 18:12发布

问题:

Is it possible for multiple scenarios to use the same Examples table?

So instead of having something like the following:

Scenario Outline: First Scenario
    Given I am viewing "<url>"
    Then I assert that the current URL "<url>"
    Examples:
      | url                |
      | https://google.com |
      | https://twitter.com|

  Scenario Outline: Second Scenario
    Given I am viewing "<url>" with route "</contactus>"
    Then I assert that "<url>" contains "contactus"
    Examples:
      | url                |
      | https://google.com |
      | https://twitter.com|

I can do something like

Scenario Outline: Reusable Example
    Examples:
      | url                |
      | https://google.com |
      | https://twitter.com|

  Scenario: First Scenario
    Given I am viewing "<url>"
    Then I assert that the current URL "<url>"

  Scenario: Second Scenario
    Given I am viewing "<url>" with route "</contactus>"
    Then I assert that "<url>" contains "contactus"

I found a similar question on StackOverflow, but merging all my scenarios in just one scenario is not an option for me. Since this question was posted in 2014, maybe there have been some advancements in the framework which I am not aware of :D

Thank you in advance.

回答1:

You can use qaf-gherkin where you can move examples in external file and use it with one or more scenario. With qaf your feature file may look like below:

Scenario Outline: First Scenario
   Given I am viewing "<url>"
   Then I assert that the current URL "<url>"
   Examples:{'datafile':'resources/testdata.txt'}

Scenario Outline: Second Scenario
Given I am viewing "<url>" with route "</contactus>"
Then I assert that "<url>" contains "contactus"
Examples:{'datafile':'resources/testdata.txt'}

And your datafile will look like:

url
https://google.com
https://twitter.com

Here is the reference.



回答2:

You might use a Background to specify steps which are equal for all scenarios. (Have a look on the link for constraints)

A feature file might look like

Feature: use of reusable Given

  Background: Reusable Example
    Given I am viewing url
      | https://google.com |
    And a search phrase is entered in the search field

  Scenario: First Scenario
    And step for first scenario

  Scenario: Second Scenario
    And step for second scenario

implementing the glue code for the Given

@Given("^I am viewing url$")
public void iAmViewing(List<String> url) throws Throwable {
    System.out.println("url = " + url);
}

edit After the question has been updated a Scenario Outline could work for both examples.

Feature: use of example

  Scenario Outline: First Scenario
    Given I am viewing "<host>" with path "<path>"
    Then I assert that the current URL is "<host><path>"

    Examples:
      | host                | path       |
      | https://google.com  | /          |
      | https://twitter.com | /contactus |