Gherkin语法中Example与Scenario的区别及替代可行性技术问询
Great question! This is a super common point of confusion for folks learning Gherkin, so let's break it down clearly:
1. Core Purpose & Usage Differences
Scenario: The standalone test case
Scenario is used to define a single, concrete, self-contained test scenario that you can run directly. It's for when you have one specific flow you want to validate.
Example of a Scenario:
Scenario: Valid user logs in successfully Given I am on the login page When I enter valid credentials Then I should be redirected to the dashboard
Example/Examples: The data feeder for parameterized tests
Example (or the official plural Examples) cannot be used on its own—it only works paired with a Scenario Outline. Its job is to provide sets of data that fill in the placeholders in the Scenario Outline, essentially generating multiple concrete Scenarios automatically.
Example of Scenario Outline + Examples:
Scenario Outline: Login validation with different credentials Given I am on the login page When I enter username "<username>" and password "<password>" Then I should see "<outcome>" Examples: | username | password | outcome | | admin | 123456 | Dashboard page | | guest | wrong123 | "Invalid credentials" error | | empty | | "Please fill all fields" error |
In this case, the Examples block creates 3 separate test scenarios under the hood—one for each row of data.
2. Can They Replace Each Other? Short Answer: No
These two keywords serve completely distinct roles, so you can't fully substitute one for the other:
- You can't use
Examplealone to define a test case—without a Scenario Outline, it's invalid Gherkin and won't run. - You could replicate the functionality of Scenario Outline + Examples by writing multiple duplicate Scenarios, but that's messy, redundant, and defeats the purpose of parameterized testing.
- Conversely, you don't need
Exampleat all if you're only testing a single, non-repeating flow—just use a Scenario.
The reason you might see them listed together in some docs is likely a shorthand reference to the "single scenario vs parameterized scenario with data" use cases, not that they're direct alternatives.
内容的提问来源于stack exchange,提问作者chinahalffull

