Cucumber: Page Factory implementation with Dependency Injection (Pico Container)

Profile picture for user devraj

In previous article we discussed how to share Web Driver instance using pico container. In this tutorial we will implement Page Factory along with dependency injection. Do copy below mentioned classes code from Web Driver article before proceeding with this article:

  • Base Class
  • Hooks Class

Also, don't forget to add pico container dependency to your pom.xml. Now, follow below steps for page factory implementation:

Feature Files

first.feature

Feature: First Feature

  @SmokeTest
  Scenario: Click on Login
    Given I am on the homepage
    And I click on login link

second.feature

Feature: Second Feature

  @SmokeTest
  Scenario: Click on Ask Doubt
    Given I am on the homepage
    And I click on ask doubt link

POM Files

FirstPOM.java

public class FirstPOM 
{
    public FirstPOM(Base base)
    {
        PageFactory.initElements(base.getDriver(), this);
    }

    @FindBy(css = "a[href='/user/login']")
    public WebElement loginLnk;
	
    public void clickLoginLnk()
    {
        loginLnk.click();
    }
}

SecondPOM.java

public class SecondPOM 
{
    public SecondPOM(Base base)
    {
        PageFactory.initElements(base.getDriver(), this);
    }

    @FindBy(css = "a[href='/ask-doubt']")
    public WebElement askDoubtLnk;
	
    public void clickAskDoubtLnk()
    {
        askDoubtLnk.click();
    }
}

Notice the changes we have done in PageFactory and Constructor, earlier we used to specify WebDriver instance in constructor, this time we have passed Base Class instance in constructor and in page factory we are giving reference to driver using base.getDriver().

Step Definition Files

FirstSD.java

public class FirstSD 
{
    WebDriver driver;
    Base base;
    FirstPOM firstPOM;
	
    public FirstSD(Base base)
    {
        this.base = base;
        this.driver = base.getDriver();
        firstPOM = new FirstPOM(base);		
    }
	
    @When("I am on the homepage")
    public void i_visit_the_homepage()
    {
        driver.get("https://www.programsbuzz.com");
    }
	
    @When("I click on login link")
    public void i_click_on_login_link()
    {
        firstPOM.clickLoginLnk();
    }	
}

Here use Page Factory the same way you do in Selenium.

SecondSD.java

public class SecondSD 
{
    Base base;
    SecondPOM secondPOM;
	
    public SecondSD(Base base)
    {
        this.base = base;
        secondPOM = new SecondPOM(base);		
    }
	
    @When("I click on ask doubt link")
    public void i_click_on_ask_doubt_link()
    {
        secondPOM.clickAskDoubtLnk();
    }
}

Notice we have not declared WebDriver instance in this class because we are not using driver instance here directly. You can execute your project by using @SmokeTest tag.

Video Tutorial: Cucumber Page Factory Implementation with Pico Container