Search code examples
javaseleniumpageobjectspage-factory

What could be the use case to return a object in Page Factory design pattern?


I've browsed over internet to get the relevant info but no luck. The example code is given below :

public class HomePage 
{
    @FindBy(id = "fname")
    WebElement name;

    @FindBy(id = "email")
    WebElement email;

    @FindBy(id = "password")
    WebElement password;

    @FindBy(id = "passwordConf")
    WebElement confPassword;

    public HomePage fillFormDetails(String firstname, String emailid)
    {
        name.sendKeys(firstname);
        email.sendKeys(emailid);

        return this;
    }

    public void fillPass(String pass)
    {
        password.sendKeys(pass);

    }   
}

I want to know why we are returning the object while calling fillFormDetails(String firstname, String emailid) method ?

What could be the usecases so we can use this to manage our code efficiency ?


Solution

  • The returned object is used when you want to us methods chaining

    HomePage homePage = new HomePage();
    homePage
        .fillFormDetails(firstName, email)
        .fillPass(pass);
    

    As a side note, better design is to split all the actions to separated methods, instead of just some of them

    public HomePage fillFirstName(String firstName)
    {
        name.sendKeys(firstName);
    
        return this;
    }
    
    public HomePage fillEmail(String email)
    {
        email.sendKeys(email);
    
        return this;
    }
    
    public void fillPass(String pass)
    {
        password.sendKeys(pass);
    }
    

    And in the test

    HomePage homePage = new HomePage();
    homePage
        .fillFirstName(firstName)
        .fillEmail(email)
        .fillPass(pass);