cucumbercucumber-jvm

Is there a way to use variables in Cucumber Examples data table?


Basically, I was looking for a way to use some kind of Java variable in Cucumber Examples data table. So that post-execution, when a report is generated, I should be able to view the current value of variable used as part of a particular Step in place of the referenced data table cell. Consider today's date or timestamp, for example, Since I do not want to hard code these variables. Without the use of variables, all scenarios looks the same.


Solution

  • What you are asking for isn't a good practice, just the opposite.

    When the code depends on current datetime, it is a good practice to mock the current datetime for testing purpose.

    You can either pass the current datetime as an argument, or to inject it.

    When testing, you pass a hardcoded datetime, which would be a precondition of the test case.

    When running the app in production, you pass the real current datetime.

    Java has an useful type for mocking current datetime called Clock.

    UPDATE:

    Regardless to mock datetime or not, you cannot use variables in Cucumber scenarios because it has no sense. BDD is about providing concrete examples with concrete data. Variables used in scenario outline are just a way to put together multiple scenarios (one for each combination of values we give to variables in a datatable).