Skip to main content

Cucumber Optional Capture Groups

An Optional Capture group eliminates the duplication of Step Definitions and can definitely improve the readability of Feature files.

Consider 2 Steps where there is just the word difference of "No" or "Not" and remaining sentence is same. I am sure you will write 2 steps if you are not aware of captured groups.

Same step definition can be used for both positive and negative assertion using option capture group. We use pipe (|) to create optional group e.g ( see| do not see).

Cucumber Optional Parameter

In below feature file check positive and negative Steps:

 #Example of Optional Capture Group
  Scenario: Keyword Search
    When I fill "search textbox" with "dress"
    Then I click "search button"
    Then I see link "TOP SELLERS"
    Then I do not see link "TOP SALE"

Cucumber Optional Parameter Java

Both Negative and Positive will call same Step Definition

@Then("^I( see| do not see) link \"([^\"]*)\"$")
public void i_should_see_link(String optionalValue, String linkText) 
  Boolean expectedValue = false;
  Boolean linkPresent = driver.findElements(By.linkText(linkText)).size() > 0;
  if(optionalValue.equals(" do not see"))
    expectedValue = false;
  else if(optionalValue.equals(" see"))
    expectedValue = true;

Check in above example how we have used same step Definition for positive or negative Step. Here you have received value of see and do not see as an argument using variable optionValue.

Submitted by tgoswami on August 30, 2020

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.


At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.