Sharing State Between Cucumber Steps with Dependency Injection

Sharing State Between Cucumber Steps with Dependency Injection

When using Cucumber, if you want to share state between multiple step definition files, you’ll need to use dependency injection (DI). There are several options: PicoContainer, Spring, OpenEJB, etc. If you’re not already using DI, then I recommend PicoContainer. Otherwise, use the one that’s already in use, because you should only have one.

First thing you’ll need to do is add the dependency to your pom file:

Next, create a new class that holds the common data. For example:

Then, in each of your step definition files that you want to use this common data, you can add a constructor that takes StepData as an argument. This is where the injection occurs. For example:

Then you can use stepData to access all of the common fields needed across your step definition classes. For example, I can split this BookStepDefinitions class into two classes:

Then in another file:

This will allow you to share the state of the fields in StepData with all of your step definition files.

Angie Jones
  • Oscar Barrios Torrero
    Hi Angie!
    Thanks for sharing this post! I used to use DI as Java Backend Developer and when I inherited my current Cucumber test framework made in Ruby, I had doubts about how we were passing state between step definitions.
    I wonder what could be the best way to share states using Cucumber for Ruby. In my inherited project, we use global variables for this case.
    We make very limited use of them, right now the only case that comes to my mind is the reuse of the output of a console command between different steps.
    What do you think about it?
    Thank you and have a good day!
    May 9, 2020 at 3:52 am Reply
  • Ibrahim

    Can you also show how we can use it using Spring? Thanks.

    October 14, 2020 at 1:35 pm Reply
  • Michael Smeeth

    Hello Angie, i have a quick question. Well i have tried this example but i am getting java.lang.NullPointerException when assigning stepData.json = stepData.response.then().statusCode(statusCode);

    June 23, 2021 at 8:22 am Reply

Post a Comment