Search code examples
javacucumberbddcucumber-jvmcucumber-java

How do I insert a string variable into my step definition in Cucumber-JVM?


I'd want to insert a predefined string into my step definition in Cucumber using java. Here's what I have:

Java Code

public String temp = "hello";
//insert temp into my step:
@Then("^the "+temp+" should be empty$")
public void the_should_be_empty() throws Throwable {
    //do things
}

But I keep getting this error:

"The value for annotation attribute Then.value must be a constant expression"

So, how do I insert a string into my capturing step?

=============

More Info

I am trying to have a set list of "global keywords" used in many of my BDD step definitios. So when I add a new "global keyword", it will be changed in all my BDD. For example (red|yellow|green) could be used in 10 different BDD steps, and I want to add blue without changing all 10 steps. Instead I want a String variable that contains the list, then insert this variable into my BDD.


Solution

  • The short answer is: "You don't".

    The longer is that the value in the annotation must be a constant. It cant be something that is constructed run time.

    The way Cucumber matches steps between Java and scenarios is by using the regular expression you define in the annotation. The process fails if the value is constructed run time. The Cucumber runner will locate and use all the regular expressions found in the step implementations and then search the feature files to match code with scenario steps.

    This is why you can't build the string to match against run time.

    It would be interesting to understand why you want to build the string run time. What are you trying to achieve? A consequence of creating many different strings is that there must be many different steps in your scenarios that should match. To me, it feels like you have misunderstood something. Please share what you are trying to achieve and maybe we can help you with another approach.