<Cucumber-JVM> pass values between steps in cucumber

How do I pass the values between two steps in cucumber JVM?

In the following scenario, I want to access username provided When step in Then step. How do I pass the values between two steps in cucumber JVM? Currently I'm accessing those by saving that value into a public variable. Is the approach correct (or) any other way I can access those between the steps?

Scenario:

Given user is on login page When user enters username as user1 and password as pass1 And clicked on login button Then post login page is displayed

@When("^user enters username as ([^\"]*) and password as ([^\"]*)$")
public void enterLoginDetails(String username,String password){
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
}

In the following step definition, I want to access username from the previous step definition

@Then("^post login page is displayed$")
public void postLoginValidation(){
// i would like access username and verify username is displayed
}

Thanks in Advance


Best Solution :

If you are using scenario outline:

When user enters username as <username> and password as <password>
Then post login page is displayed with <username>

Examples:

| username|password|
|Kiran|1234|

Step Defination Code:

@When("user enters username as (.*) and password as (.*)")
public void enterLoginDetails(String userName,String password)
{
    //You will get userName=Kiran and Password=1234

}
@Then("post login page is displayed with (.*)")
public void postLoginValidation(String userName)
{
   //You will be access the same username which is you are passing while login
  ////You will get userName=Kiran
}


public your class {

    private String usr;

    @When("^user enters username as ([^\"]*) and password as ([^\"]*)$")
    public void enterLoginDetails(String username,String password){

      usr = username;
      ...
    }

    @Then("^post login page is displayed$")
    public void postLoginValidation(){

      //do something with usr

    }

}


You could share state between steps using variables, as suggested by Bala.

Another solution in Java is to use dependency injection. Cucumber-JVM support many different dependency injection frameworks. One of them is Spring. Dependencies can be made available where they are needed using annotations. Using Spring is a good option if your project is already using Spring. Otherwise it might be too big and cumbersome.

An easy to use alternative to Spring, is to use PicoContainer.

For more information on either, please have a look at:

http://www.thinkcode.se/blog/2017/06/24/sharing-state-between-steps-in-cucumberjvm-using-spring

http://www.thinkcode.se/blog/2017/04/01/sharing-state-between-steps-in-cucumberjvm-using-picocontainer