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

I am using cucumber with java to test my application,
I would like to know if it is possible to take the object returned from the first step of the script and use it in other steps. Here is an example of the desired function 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 prefer not to use variables in the class
(Because then all the method variables will be at the class level)
but I'm not sure if this is possible.

Can the return value in the method be used as input in the next step?

+3


source to share


1 answer


There is no direct support for using return values ​​from step methods in other steps. As you said, you can achieve state sharing through instance variables, which is great for small examples. Once you get more steps and want to refactor them into separate classes, you might run into problems.

An alternative would be to encapsulate the state in your own class that manages it using ThreadLocals

, you need to make sure to initialize or reset this state, perhaps using interceptors.

If you are using a dependency injection framework like spring you can use the provided script scope.



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

      

This context object can then be injected into multiple classes containing stages.

+2


source







All Articles