Search code examples
javaseleniumcucumber-java

Cucumber 4 Optional Words?


@Then("a topic is (not) displayed on the chat icon of the menu")

Basically I want the not to be optional if possible? Previously it was (is|is not).

Adding that is|is not is part of the capturing group, entered as a String in the stepdef.


Solution

  • If you want to use regular expressions you should start your strings with ^ and/or end them with $. Otherwise Cucumber will treat them as Cucumber expressions. So:

    @Then("^a topic (is|is not) displayed on the chat icon of the menu$")
    public void a_topic_is_displayed(String isDisplayed){
    
    }
    

    If you do want to use Cucumber expressions then you'll have to capture the modifier in a parameter type. So:

    @Then("a topic {isOrIsNot} displayed on the chat icon of the menu")
    public void a_topic_is_displayed(boolean isDisplayed){
    
    }
    

    And you'd register a parameter type to convert the string to a boolean:

    typeRegistry.defineParameterType(new ParameterType<>(
        "isOrIsNot",                     // name
        "is|is not",                     // regexp
        boolean.class,                   // type
        (String arg) -> "is".equals(arg) // transformer function
    ))