Search code examples
javaseleniumpageobjectsserenity-bddcucumber-serenity

Selenium page object model, how to pass variable from one page class to another?


I'm trying to see if there's a way to pass a variable from one page object to another? I'm using Serenity BDD framework for my java project. On one page I'm creating and naming an item, and then I go to another page where I'm trying to locate that item, in a table for example. I'm running into an issue where the variable I'm calling on the second page is null.

Each page has its own page class and this is a sample code:

public class Page1 extends PageObject{
String itemName;
private String savedItemName;

public String getSavedItemName(){
     return savedItemName;
}

public String createItemAndNameIt(){
     //some action to create an item
     //some action to save the item with a given name
     //assigned from itemName which is fed from environment variable

     savedItemName = itemName;
     return itemName;
}

}

Next step is my code is going into next page and calling savedItemName variable.

public class Page2 extends PageObject{

Page1 page1Steps = New Page1();
String recoveredItemName;


public void searchForItem{
     //perform some action to get a list of items
     //calling a function that searches page for item
     //which accepts element to search and string to search for
    searchForElement(webElement,page1Steps.getSavedItemName());

}

}

When I'm calling page1Steps.getSavedItemName() that returns null. I suspect that the culprit could be webdriver when switching between pages the value which was saved in the previous page is not accessible to the new page? Looking for any advice on how to do this sucessfully.


Solution

  • With help of John Ferguson, this is easily solved by using the following:

         Serenity.setSessionVariable("customerName").to("Jim”);
         String customerName = sessionVariableCalled("customerName”);