2
votes

Does anyone know if cucumber/Java supports the functionality of multiple steps to access the same stepDefinition?

What I am trying to achieve is to use as a Given a step that at the moment is used as a When (in another more complex test where the current When becomes just a precondition)

In my previous experience (Specflow/.Net) I could use something like

[Given(@"the user added a (.*) to the cart")]
[When(@"the user adds a (.*) to the cart")]
public void WhenTheUserAddsATotheCart(string product){
    ////code that adds to the cart
}

If I use the same methodology as in Specflow, a DuplicateStepDefinitionException is thrown. Because Cucumber doesn't take the key words (Given, When etc.) into consideration when matching the Steps with the step definitions. Cucumber only looks for a regEx in the step definitions so I would need to have only one step definition (Given OR When). Meaning

[When(@"the user adds a (.*) to the cart")]

will also match

[Given(@"the user adds a (.*) to the cart")]

My problem is that we use the Given at past tense and the When at present tense.

So the question is: how can I use the same implementation for two step definitions?

The only solution I see is to extract the contains of the method that implements the Given into another method and call it under both Given step definition and under When.Something like:

[Given(@"the user added a (.*) to the cart")]
public void GivenTheUserAddedATotheCart(string product){
    addToTheCart(product);
}

[When(@"the user adds a (.*) to the cart")]
public void WhenTheUserAddsATotheCart(string product){
    addToTheCart(product);
}

public void addToTheCart(String product){
////code that adds to the cart
}

... but I don't really find this a nice solution

1
I understand this is not answering your question but just in case, if you ever want to switch to (IMO superior) combo Python-Behave, then there you can use the generic STEP keyword in place of GIVEN, WHEN or THEN. - Alichino

1 Answers

1
votes

I have found multiple discussions around this topic in the cucumber repo but most of them are specific to the cucumber-jvm implementation:

This is a controversial topic and as I far as I understood no official support for this feature has been implemented but there are some references on how this could be achieved. On the example shown, since the steps are similar I would just extended the regular expression on the step definition to match both steps:

[Given(@"the user add(s|ed) a (.*) to the cart")]
public void WhenTheUserAddsATotheCart(string tense, string product){
    ////code that adds to the cart
}

Of course, this solution produces an additional parameter on the method which is useless unless you are planning to follow a different path when the step is executed in the past (Given) or in the present (When).