Page Object Model with Selenium and Cucumber

HOME

In this tutorial, I’ll create a BDD Framework for the testing of web applications using Page Object Model . This framework consists of

  1. Cucumber Java – 6.8.1
  2. Cucumber JUnit4 – 6.8.1
  3. Java 11
  4. Maven – 3.8.1
  5. Selenium – 3.141.59

What Is Page Object Model (POM)?

Page Object model is an object design pattern in Selenium, where web pages are represented as classes, and the various elements on the page are defined as variables in the class and all possible user interactions can then be implemented as methods in the class.

What is Cucumber?

Cucumber is one such open source tool, which supports Behavior Driven Development(BDD). In simple words, Cucumber can be defined as a testing framework, driven by plain English. It serves as documentation, automated tests, and a development aid – all in one.

Steps to setup Cucumber Test Automation Framework using Page Object Model

  1. Download and Install Java on system
  2. Download and setup Eclipse IDE on system
  3. Setup Maven on System
  4. Create a new Maven Project
  5. Create a source folder – src/test/resources to create test scenarios in Feature file
  6. Add Selenium and Cucumber dependencies to the project
  7. Add Maven Compiler Plugin
  8. Create a feature file under src/test/resources
  9. Create the Step Definition class or Glue Code for the Test Scenarios
    1. Create a Java Class for each page where define WebElements as variables using Annotation @FindBy and Create methods for actions performed on WebElements.
    2. Create a Java Class called Definition where we will create the Test Code related to Given,When, Then of Feature file
  10. Create a Cucumber Runner class
  11. Run the tests from JUnit
  12. Run the tests from Command Line
  13. Cucumber Report Generation

Project Structure

Step 1- Download and Install Java

Cucumber and Selenium needs Java to be installed on the system to run the tests. Click here to know How to install Java.

Step 2 – Download and setup Eclipse IDE on system

The Eclipse IDE (integrated development environment) provides strong support for Java developer. Click here to know How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add a number of dependencies to the project. Click here to know How to install Maven.

Step 4 – Create a new Maven Project

File -> New Project-> Maven-> Maven project-> Next -> Enter Group ID & Artifact ID -> Finish

Click here to know How to create a Maven project

Step 5 – Create source folder src/test/resources to create test scenarios in Feature file

A new Maven Project is created with 2 folders – src/main/java and src/test/java. To create test scenarios, we need a new source folder called – src/test/resources. To create this folder, right click on your maven project ->select New ->Java and then Source Folder.

Mention the source folder name as src/test/resources and click Next button. This will create a source folder under your new Maven project as shown in the below image.

Step 6 – Add Selenium and Cucumber dependencies to the project

Add below mentioned Selenium and Cucumber dependencies to the project.

<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>6.8.1</version>
    </dependency>
 
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-junit</artifactId>
      <version>6.8.1</version>
      <scope>test</scope>
     </dependency>
 
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>

Step 7 – Add Maven Compiler Plugin

The compiler plugin is used to compile the source code of a Maven project. This plugin has two goals, which are already bound to specific phases of the default lifecycle:

  • compile – compile main source files
  • testCompile – compile test source files
<build>
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>3.7.0</version>
         <configuration>
           <source>11</source>
           <target>11</target>
            <encoding>UTF-8</encoding>          
         </configuration>
       </plugin>                
       </plugins>
   </build>

Step 8 – Create a feature file under src/test/resources

Create a folder with name features. Now, create the feature file in this folder. The feature file should be saved with extension .feature. This feature file contain the test scenarios created to test the application. The Test Scenarios are written in Gherkins language in the format of Given, When, Then, And, But.

Below is an example of Test Scenario in feature file.

Feature: Login to HRM Application 

   @ValidCredentials
   Scenario: Login with valid credentials
    
    Given User is on HRMLogin page
    When User enters username as "Admin" and password as "admin123"
    Then User should be able to login sucessfully and new page open

Step 9 – Create the Step Definition class or Glue Code for the Test Scenario

Create a Java Class for each page where define WebElements as variables using Annotation @FindBy and Create methods for actions performed on WebElements. Here, I’m going to create 2 classes – Login and Home.

Login class contains WebElements which are identified by @FindBy annotation as shown below:-

@FindBy(name = "txtUsername")
WebElement userName;

It also create methods for the action to be performed on these webelements as shown below:-

public void login(String strUserName, String strPassword) {
 
           // Fill user name
           this.setUserName(strUserName);
 
           // Fill password
           this.setPassword(strPassword);
 
           // Click Login button
           this.clickLogin();
     }
}

The initElements is a static method of PageFactory class which is used to initialize all the web elements located by @FindBy annotation.Only after the WebElements are initialized, they can be used in the methods to perform actions.

public Login(WebDriver driver) {
           this.driver = driver;
           // This initElements method will create all WebElements
           PageFactory.initElements(driver, this);
     }

Below is the sample code of Login page.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class Login {

	/**
	 * 
	 * All WebElements are identified by @FindBy annotation
	 * 
	 */

	WebDriver driver;

	@FindBy(name = "txtUsername")
	WebElement userName;

	@FindBy(name = "txtPassword")
	WebElement password;

	@FindBy(id = "logInPanelHeading")
	WebElement titleText;

	@FindBy(id = "btnLogin")
	WebElement login;

	public Login(WebDriver driver) {

		this.driver = driver;

		// This initElements method will create all WebElements
		PageFactory.initElements(driver, this);
	}

	// Set user name in textbox
	public void setUserName(String strUserName) {
		userName.sendKeys(strUserName);
	}

	// Set password in password textbox
	public void setPassword(String strPassword) {
		password.sendKeys(strPassword);
	}

	// Click on login button
	public void clickLogin() {
		login.click();
	}

	// Get the title of Login Page
	public String getLoginTitle() {
		return titleText.getText();
	}

	public void login(String strUserName, String strPassword) {

		// Fill user name
		this.setUserName(strUserName);

		// Fill password
		this.setPassword(strPassword);

		// Click Login button
		this.clickLogin();

	}
}

Below is the sample code of Home page.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class HomePage {

	WebDriver driver;

	@FindBy(id = "welcome")
	WebElement homePageUserName;

	public HomePage(WebDriver driver) {
		this.driver = driver;

		// This initElements method will create all WebElements
		PageFactory.initElements(driver, this);
	}

	// Get the User name from Home Page
	public String getHomePageText() {
		return homePageUserName.getText();
	}
}

Now, we need to create the Step Definition of Feature File – LoginPageDefinitions.java.

import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

public class LoginPageDefinitions {
	String driverPath = "C:\\Users\\Desktop\\Automation\\Drivers\\geckodriver-v0.24.0-win64\\geckodriver.exe";

	WebDriver driver;

	Login objLogin;

	HomePage objHomePage;

	@Before
	public void setup() {

		// Initialize the webdriver and open the browser
		System.setProperty("webdriver.gecko.driver", driverPath);
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	/**
	 * 
	 * This test go to https://opensource-demo.orangehrmlive.com/ Verify login page title as LOGIN Panel Login to application Verify the home page using welcome
	 * message
	 * 
	 */

	@Given("User is on HRMLogin page")
	public void loginTest() {

		// Create Login Page object
		objLogin = new Login(driver);

		// Verify login page text
		String loginPageTitle = objLogin.getLoginTitle();
		Assert.assertTrue(loginPageTitle.contains("LOGIN Panel"));

	}

	@When("User enters username as {string} and password as {string}")
	public void HomeTest(String userName, String passWord) {

		// login to application
		objLogin.login(userName, passWord);

		// go the next page
		objHomePage = new HomePage(driver);
	}

	@Then("User should be able to login sucessfully and new page open")
	public void verify() {

		// Verify home page
		Assert.assertTrue(objHomePage.getHomePageText().contains("Welcome"));

	}

	@After
	public void close() {

		// Close the browser
		driver.close();
	}
}

In the above stepdefinition or glue code, @Before and @After annotations are used for Instantizing the web browser and then closing the web browser. These are JUnit annotations. We have not identified the web elements or declared the methods in this class. All these activities are done in the respective Page Classes ie Login.java and Home.java.

Step 10 – Create a JUnit Cucumber Runner class to execute the test scenarios

import org.junit.runner.RunWith;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)

@CucumberOptions(features = {
		"src/test/resources/features/HRMLoginPage.feature" }, glue = "com.cucumber.pageobjectmodel")
public class CucumberRunnerTest {

}

Note:- The name of Runner class should end with Test otherwise we can’t run the tests using Command Line.

Step 11 – Run the tests from JUnit

You can execute test script by right clicking on TestRunner class -> Run As JUnit.

Step 12 – Run the tests from Command Line

Run the below command in command prompt to run t he tests and to get the test execution report.

mvn test

Step 13 – Cucumber Report Generation

To get Cucumber Test Reports, add cucumber.properties under src/test/resources and add the below instruction in the file.

cucumber.publish.enabled=true

Below is the image of the Cucumber Report generated using Cucumber Service.

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s