Search code examples
seleniumpageobjectspage-factory

Selenium Page Objects: Why should I return this?


Reading SeleniumHQ's pageobject documentation they specify examples of returning "this" from methods that do not navigate to other pages. My question is why?

I thought maybe the state of the page object could be a reason, however the page itself (the actual UI page) may change state or refresh but the page object itself would not. Page Factory with its @FindBy annotations already ensure that each WebElement will be found every time it is called, so the state of the elements doesn't seem to be relevant this case.


Solution

  • Consider their example

    public LoginPage typeUsername(String username) {
        driver.findElement(usernameLocator).sendKeys(username);
        return this;    
    }
    
    public LoginPage typePassword(String password) {
        driver.findElement(passwordLocator).sendKeys(password);
        return this;    
    }
    
    public HomePage submitLogin() {
        driver.findElement(loginButtonLocator).submit();
        return new HomePage(driver);    
    }
    

    now assume we have create the page object create as page. If you didn't return anything your code would like

    page.typeUsername("tarun");
    page.typePassword("lalwani");
    HomePage newPage = page.submitLogin()
    

    But when you return this, it allows you to do method chaining. So I can use it like below

    HomePage newPage = page.typeUsername("tarun").typePassword("lalwani").submitLogin()
    

    As you can see it will save you some coding effort and much more elegant with IDE intellisense