Yaron
Yaron

Reputation: 41

Cucumber Java - How to use returned parameters from a step in a new step?

I'm using cucumber with java in order to test my app ,
I would like to know if it is possible to take an object returned from first scenario step and use it in other steps. Here is an example for the desirable feature file and Java code :

Scenario: create and check an object  
 Given I create an object  
 When I am using this object(@from step one)  
 Then I check the object is ok  


@Given("^I create an object$")  
    public myObj I_create_an_object() throws Throwable   {  
        myObj newObj = new myObj();  
        return newObj;  
    }  

@When("^I am using this object$")  
    public void I_am_using_this_object(myObj obj) throws Throwable   {  
        doSomething(obj);  
    }  

@Then("^I check the object is ok$")  
    public void I_check_the_object_is_ok() throws Throwable   {  
        check(obj);
    }  

I rather not to use variables in the class
(Because then all method variables will be in class level)
but i'm not sure it's possible.

Is it possible to use a return value in a method as an input in the next step?

Upvotes: 4

Views: 5600

Answers (1)

Jörn Horstmann
Jörn Horstmann

Reputation: 34054

There is no direct support for using the return values from step methods in other steps. As you said, you can achieve sharing of state via instance variables, which works fine for smaller examples. Once you get more steps and want to reorganize them into separate classes you might run into problems.

An alternative would be to encapsulate the state into its own class which manages it using ThreadLocals, you would have to make sure to initialize or reset this state, maybe using hooks.

If you are using a dependency injection framework like spring you could use the provided scenario scope.

@Component
@Scope("cucumber-glue")
public class SharedContext { ... }

This context object could then be injected into multiple classes containing the steps.

Upvotes: 2

Related Questions