javaseleniumcucumberambiguous

In cucumber, is it possible to have a single stepdefinition method for int and double datatypes, if no then how to handle these different datatypes?


In cucumber, is it possible to have a single stepdefinition method for int and double datatypes, if no then how to handle these different datatypes without changing data/parameter to a similar datatype like string or double?

For Eg.

Feature: Testing

Scenario: Test1
When User enters 1 
Then Print "Hello"

Scenario: Test2
When User enters 1.0 
Then don't print anything

When I use the following Stepdefinition with Regular Expression, matching glue code is found missing for steps "User enters 1" and "User enters 1.0" or steps are undefined error comes up.

public class test {
 
    @Then("Print {string}")
    public void print(String string) {
        System.out.println(string);
    }

    @When("^User enters (\"\\d+\\.\\d+\")$")
    public void user_enters(Double double1) {
       System.out.println(double1);
    }
    @Then("don't print anything")
    public void don_t_print_anything() {
       }
}

But when I add the suggested steps snippet to the stepdefinition(mentioned below) then io.cucumber.core.runner.AmbiguousStepDefinitionsException is thrown.

public class test {
@When("User enters {int}")
public void user_enters(Integer int1) {
   system.out.println(int1);
}

@Then("Print {string}")
public void print(String string) {
   system.out.println(string);
}

@When("User enters {double}")
public void user_enters(Double double1) {
    system.out.println(double1);
}
 @Then("don't print anything")
 public void don_t_print_anything() {
           }
}

Solution

  • Your original regex doesn't match the step

    ^User enters (\"\\d+\\.\\d+\")$
    

    Note the " that doesn't exist in the step

    When User enters 1.0
    

    Though since your steps are talking about user input you may want to capture it as a string instead, e.g:

    User enters {string}
    

    And then write a step like

    When User enters "1.0"
    

    Note the added "s.