Allure Report with Cucumber5 and TestNG

HOME

In the previous tutorial, I have explained the Integration of the Allure Report with Selenium and TestNG. In this tutorial, I will explain how to Integrate Allure Report with Cucumber5 and TestNG.

Below example covers the implementation of Allure Reports with Cucumber5, Selenium, TestNG, Java and Maven.

Pre-Requisite

  1. Java 11 installed
  2. Maven installed
  3. Eclipse or IntelliJ installed

This framework consists of:

  1. Selenium – 3.141.59
  2. Java 11
  3. Cucumber 5 – 5.7.0
  4. Maven – 3.8.1
  5. Allure Report – 2.14.0
  6. Allure Cucumber5 – 2.14.0
  7. Aspectj – 1.9.6

Implementation Steps

  1. Update Properties section in Maven pom.xml
  2. Add Cucumber5, Selenium, TestNG and Allure Cucumber5 dependencies in POM.xml
  3. Update Build Section of pom.xml in Allure Report Project.
  4. Create source folder – src/test/resources and features folder within src/test/resources to create test scenarios in Feature file
  5. Create the Step Definition class or Glue Code
  6. Create a Cucumber Runner class
  7. Run the Test and Generate Allure Report

Step 1 – Update Properties section in Maven pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <selenium.version>3.141.59</selenium.version>
    <cucumber.version>5.7.0</cucumber.version>
    <testng.version>7.4.0</testng.version>
    <allure.cucumber5.version>2.14.0</allure.cucumber5.version>
    <maven.compiler.plugin.version>3.5.1</maven.compiler.plugin.version>
    <maven.surefire.plugin.version>3.0.0-M5</maven.surefire.plugin.version>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
    <aspectj.version>1.9.6</aspectj.version>
    <allure.maven.version>2.10.0</allure.maven.version>
  </properties>

Step 2 – Add Cucumber5, Selenium, TestNG, Allure-Cucumber5 and Allure-TestNG dependencies in POM.xml

<dependencies>
  <!--Cucumber Dependencies-->  
    <dependency>
       <groupId>io.cucumber</groupId>
       <artifactId>cucumber-java</artifactId>
       <version>${cucumber.version}</version>
    </dependency>
 
  <!--Selenium Dependency-->
    <dependency>
       <groupId>org.seleniumhq.selenium</groupId>
       <artifactId>selenium-java</artifactId>
       <version>${selenium.version}</version>
    </dependency>
  <!--Cucumber TestNG Dependency-->
    <dependency>
       <groupId>io.cucumber</groupId>
       <artifactId>cucumber-testng</artifactId>
       <version>${cucumber.version}</version>
        <scope>test</scope>
    </dependency>
  <!--Hamcrest Dependency-->
    <dependency>
       <groupId>org.hamcrest</groupId>
       <artifactId>hamcrest</artifactId>
       <version>2.2</version>
       <scope>test</scope>
    </dependency>
    
  <!--Allure Cucumber Dependency-->   
      <dependency>
         <groupId>io.qameta.allure</groupId>
         <artifactId>allure-cucumber5-jvm</artifactId>
         <version>${allure.cucumber5.version}</version>
    </dependency>  
</dependencies>

Step 3 – Update Build Section of pom.xml in Allure Report Project

<build>
    <plugins>   
      <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source> 
                    <target>${maven.compiler.target}</target> 
                </configuration>
            </plugin>
     
     <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
             <version>${maven.surefire.plugin.version}</version>
            <configuration>
                 <suiteXmlFiles>
                        <suiteXmlFile>TestNG.xml</suiteXmlFile>
                    </suiteXmlFiles>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                    -Dcucumber.options="--plugin io.qameta.allure.cucumber5jvm.AllureCucumber5Jvm"
                </argLine>
                        
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
        </plugin>
        
         <plugin>
                <groupId>io.qameta.allure</groupId>
                <artifactId>allure-maven</artifactId>
                <version>${allure.maven.version}</version>
                <configuration>
                    <reportVersion>${allure.version}</reportVersion>
                </configuration>
            </plugin>
      </plugins>      
   </build>

Step 4 – Create source folder – src/test/resources and features folder within src/test/resources to create test scenarios in Feature file

Feature file should be saved as an extension of .feature. Add the test scenarios in this feature file. I have added sample test scenarios. In this feature file. The test scnerios are written in Gherkins language.

@LoginPage @TestNG
@severity=blocker
Feature: Feature - Login to HRM Application 
 
   @ValidCredentials
   Scenario: Scenario - Login with valid credentials 
     
    Given User is on Home page
    When User enters username as "Admin"
    And User enters password as "admin123"
    Then User should be able to login sucessfully
    
   @InvalidCredentials
   Scenario Outline: Scenario -Login with invalid credentials
   
    Given User is on Home page
    When User enters username as "<username>"
    And User enters password as "<password>"
    Then Error message "<message>" should be displayed
    
    Examples:
    |username  |password  |message                         |
    |admin     |admin     |Invalid credentials             |
    |          |admin123  |Username can be empty           | 
    |Admin     |          |Password can be empty           |
    |          |          |Username cannot be empty        |

Step 5 – Create the Step Definition class or Glue Code

CommonDefinitions.java

package com.example.CucumberAllureReportDemo.definitions;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
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.Scenario;
public class CommonDefinitions {
	protected static WebDriver driver;
	@Before
	public void setup() {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}
	@After
	public void tearDown(Scenario scenario) {
		try {
			String screenshotName = scenario.getName().replaceAll("", "_");
			if (scenario.isFailed()) {
				TakesScreenshot ts = (TakesScreenshot) driver;
				byte[] screenshot = ts.getScreenshotAs(OutputType.BYTES);
				scenario.attach(screenshot, "img/png", screenshotName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		driver.quit();
	}
}

LoginPageDefinition.java

public class LoginDefinition {
	@Given("User is on Home page")
	public void userOnHomePage() {
		CommonDefinitions.driver.get("https://opensource-demo.orangehrmlive.com/");
	}
	@When("User enters username as {string}")
	public void entersUsername(String userName) throws InterruptedException {
		System.out.println("Username Entered");
		CommonDefinitions.driver.findElement(By.name("txtUsername")).sendKeys(userName);
	}
	@When("User enters password as {string}")
	public void entersPassword(String passWord) throws InterruptedException {
		System.out.println("Password Entered");
		CommonDefinitions.driver.findElement(By.name("txtPassword")).sendKeys(passWord);
		CommonDefinitions.driver.findElement(By.id("btnLogin")).submit();
	}
	@Then("User should be able to login sucessfully")
	public void sucessfulLogin() throws InterruptedException {
		String newPageText = CommonDefinitions.driver.findElement(By.id("welcome")).getText();
		System.out.println("newPageText :" + newPageText);
		assertThat(newPageText, containsString("Welcome"));
	}
	@Then("Error message {string} should be displayed")
	public void unsucessfulLogin(String message) throws InterruptedException {
		String errorMessage = CommonDefinitions.driver.findElement(By.id("spanMessage")).getText();
		System.out.println("Error Message :" + errorMessage);
		Assert.assertEquals(errorMessage, message);
	}
}

Step 6 – Create a Cucumber Runner class

We need to create a class called Runner class to run the tests. This class will use the JUnit annotation @RunWith(), which tells JUnit what is the test runner class.

import org.testng.annotations.Test;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
@Test
@CucumberOptions(plugin = { "pretty }, tags = "", features = "src/test/resources/features/Login.feature", glue = "com.example.CucumberAllureReportDemo.definitions")
public class CucumberRunnerTests extends AbstractTestNGCucumberTests {
}

Note:- @Test annotation marks this class as part of the test. So, if we will remove this annotation, the Allure Report execute CucumberRunnerTests as a seperate test suite, so there will be duplicate results.

Step 7 – Create testng.xml for the project

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite1">
  <test name = "Test Demo">
    <classes>
          <class name = "com.example.CucumberAllureReportDemo.runner.CucumberRunnerTests"/>
     </classes>  
   </test>
</suite>

Step 8 – Run the Test and Generate Allure Report

To run the tests, use the below command

mvn clean test

In the below image, we can see that two tests are failed and three passed out of five tests.

This will create allure-results folder with all the test report. These files will be use to generate Allure Report.

Use the below comand to generate the Allure Report

allure serve

This will generate the beautiful Allure Test Report as shown below.

Allure Report Dashboard

Categories in Allure Report

Categories tab gives you the way to create custom defects classification to apply for test results. There are two categories of defects – Product Defects (failed tests) and Test Defects (broken tests).

Suites in Allure Report

On the Suites tab a standard structural representation of executed tests, grouped by suites and classes can be found. Here, we have 2 suits – Feature and Surefire test. Surefire test are executed from CucumberRunnerTests.

Graphs in Allure Report

Graphs allow you to see different statistics collected from the test data: statuses breakdown or severity and duration diagrams.

Timeline in Allure Report

Timeline tab visualizes retrospective of tests execution, allure adaptors collect precise timings of tests, and here on this tab they are arranged accordingly to their sequential or parallel timing structure.

Behaviors of Allure Report

This tab groups test results according to Epic, Feature and Story tags.

Packages in Allure Report

Packages tab represents a tree-like layout of test results, grouped by different packages.

When we don’t use @Test in CucumberRunnerTests.java, then as mentioned above the Allure report will have duplicate details as shown below:-

Allure Report with Cucumber5 and JUnit4

HOME

In the previous tutorial, I have explained the Integration of the Allure Report with Selenium and JUnit4. In this tutorial, I will explain how to Integrate Allure Report with Cucumber5 and JUnit4.

Below example covers the implementation of Allure Reports in Selenium using JUnit4, Java and Maven.

Pre-Requisite

  1. Java 11 installed
  2. Maven installed
  3. Eclipse or IntelliJ installed

This framework consists of:

  1. Selenium – 3.141.59
  2. Java 11
  3. Cucumber 5 – 5.7.0
  4. Maven – 3.8.1
  5. Allure Report – 2.14.0
  6. Allure Cucumber5 – 2.14.0
  7. Allure JUnit4 – 2.14.0
  8. Aspectj – 1.9.6

Implementation Steps

  1. Update Properties section in Maven pom.xml
  2. Add Cucumber5, Selenium, JUnit4, Allure Cucumber5 and Allure-JUnit4 dependencies in POM.xml
  3. Update Build Section of pom.xml in Allure Report Project.
  4. Create source folder – src/test/resources and features folder within src/test/resources to create test scenarios in Feature file
  5. Create the Step Definition class or Glue Code
  6. Create a Cucumber Runner class
  7. Run the Test and Generate Allure Report

Step 1 – Update Properties section in Maven pom.xml

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <selenium.version>3.141.59</selenium.version> 
    <cucumber.version>5.7.0</cucumber.version>
    <allure.cucumber5.version>2.14.0</allure.cucumber5.version>
    <allure.junit4.version>2.14.0</allure.junit4.version>
    <maven.compiler.plugin.version>3.5.1</maven.compiler.plugin.version>
    <maven.surefire.plugin.version>3.0.0-M5</maven.surefire.plugin.version>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
    <aspectj.version>1.9.6</aspectj.version>
    <allure.version>2.14</allure.version>
  </properties>

Step 2 – Add Cucumber5, Selenium, JUnit4, Allure-Cucumber5 and Allure-JUnit4 dependencies in POM.xml

 <dependencies>
     
     <!--Cucumber Dependencies-->     
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>${cucumber.version}</version>
    </dependency>
    
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-junit</artifactId>
      <version>${cucumber.version}</version>
       <scope>test</scope>
    </dependency>
 
   <!--Selenium Dependency-->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>${selenium.version}</version>
    </dependency>   

   <!--Hamcrest Dependency-->
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest</artifactId>
      <version>2.2</version>
      <scope>test</scope>
    </dependency>
    
   <!--Allure Cucumber Dependency-->     
      <dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-cucumber5-jvm</artifactId>
        <version>${allure.cucumber5.version}</version>
    </dependency>
    
     <!--Allure Reporting Dependency-->     
    <dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-junit4</artifactId>
        <version>${allure.junit4.version}</version>
        <scope>test</scope>
    </dependency>

  </dependencies>

Step 3 – Update Build Section of pom.xml in Allure Report Project

<build>
   <plugins>
  
       <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source> 
                    <target>${maven.compiler.target}</target>
                </configuration>
         </plugin>
     
       <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
             <version>${maven.surefire.plugin.version}</version>
            <configuration>
                 <systemPropertyVariables>
                        <allure.results.directory>${project.build.directory}/allure-results</allure.results.directory>
                    </systemPropertyVariables>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                    -Dcucumber.options="--plugin io.qameta.allure.cucumber5jvm.AllureCucumber5Jvm"
                </argLine>
                        
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
         </plugin>
       
     </plugins> 
  </build>

Step 4 – Create source folder – src/test/resources and features folder within src/test/resources to create test scenarios in Feature file

Feature file should be saved as an extension of .feature. Add the test scenarios in this feature file. I have added sample test scenarios. In this feature file, I have created a scenario for successful login and one Scenario Outline for failed login. The test scenarios are written in Gherkins language.

@LoginPage @Junit4

@severity=blocker

Feature: Feature - Login to HRM Application 
 
   @ValidCredentials
   Scenario: Scenario - Login with valid credentials 
     
    Given User is on Home page
    When User enters username as "Admin"
    And User enters password as "admin123"
    Then User should be able to login sucessfully
    
   @InvalidCredentials
   Scenario Outline: Scenario -Login with invalid credentials
   
    Given User is on Home page
    When User enters username as "<username>"
    And User enters password as "<password>"
    Then Error message "<message>" should be displayed
    
    Examples:
    |username  |password  |message                         |
    |admin     |admin     |Invalid credentials             |
    |          |admin123  |Username cannot be empty        | 
    |Admin     |          |Password cannot be empty        |
    |          |          |Username can be empty           |

Step 5 – Create the Step Definition class or Glue Code

public class LoginDefinition {

	@Given("User is on Home page")
	public void userOnHomePage() {

		CommonDefinitions.driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	@When("User enters username as {string}")
	public void entersUsername(String userName) throws InterruptedException {

		System.out.println("Username Entered");
		CommonDefinitions.driver.findElement(By.name("txtUsername")).sendKeys(userName);

	}

	@When("User enters password as {string}")
	public void entersPassword(String passWord) throws InterruptedException {

		System.out.println("Password Entered");
		CommonDefinitions.driver.findElement(By.name("txtPassword")).sendKeys(passWord);

		CommonDefinitions.driver.findElement(By.id("btnLogin")).submit();
	}

	@Then("User should be able to login sucessfully")
	public void sucessfulLogin() throws InterruptedException {

		String newPageText = CommonDefinitions.driver.findElement(By.id("welcome")).getText();
		System.out.println("newPageText :" + newPageText);
		assertThat(newPageText, containsString("Welcome"));

	}

	@Then("Error message {string} should be displayed")
	public void unsucessfulLogin(String message) throws InterruptedException {

		String errorMessage = CommonDefinitions.driver.findElement(By.id("spanMessage")).getText();
		System.out.println("Error Message :" + errorMessage);
		Assert.assertEquals(errorMessage, message);

	}

}

CommonDefinitions.java

public class CommonDefinitions {

	protected static WebDriver driver;

	@Before
	public void setup() {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");

		driver = new FirefoxDriver();

		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@After
	public void tearDown(Scenario scenario) {
		try {
			String screenshotName = scenario.getName().replaceAll("", "_");
			if (scenario.isFailed()) {
				TakesScreenshot ts = (TakesScreenshot) driver;
				byte[] screenshot = ts.getScreenshotAs(OutputType.BYTES);
				scenario.attach(screenshot, "img/png", screenshotName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		driver.quit();
	}

}

Step 6 – Create a Cucumber Runner class

We need to create a class called Runner class to run the tests. This class will use the JUnit annotation @RunWith(), which tells JUnit what is the test runner class.

import org.junit.runner.RunWith;

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

@RunWith(Cucumber.class)
@CucumberOptions(features = {
		"src/test/resources/features/Login.feature" }, glue = "com.example.CucumberJunitAllureReportDemo.definitions", plugin = {
				"pretty", "html:test-output", "json:target/cucumber-report/cucumber.json" })

public class CucumberRunnerTests {

}

Step 7 – Run the Test and Generate Allure Report

To run the tests, use the below command

mvn clean test

In the below image, we can see that one test is failed and four passed out of five tests.

This will create allure-results folder with all the test report. These files will be use to generate Allure Report.

Change current directory to target directory and then the below comand to generate the Allure Report

allure serve

This will generate the beautiful Allure Test Report as shown below.

Allure Report Dashboard

It shows detail of all the test steps and the screenshot of the failed test step also as shown below.

Categories in Allure Report

Categories tab gives you the way to create custom defects classification to apply for test results. There are two categories of defects – Product Defects (failed tests) and Test Defects (broken tests).

Suites in Allure Report

On the Suites tab a standard structural representation of executed tests, grouped by suites and classes can be found.

Graphs in Allure Report

Graphs allow you to see different statistics collected from the test data: statuses breakdown or severity and duration diagrams.

Timeline in Allure Report

Timeline tab visualizes retrospective of tests execution, allure adaptors collect precise timings of tests, and here on this tab they are arranged accordingly to their sequential or parallel timing structure.

Behaviors of Allure Report

This tab groups test results according to Epic, Feature and Story tags.

Packages in Allure Report

Packages tab represents a tree-like layout of test results, grouped by different packages.

Allure Report with Selenium and JUnit5

HOME

In the previous tutorial, I have explained the Integration of the Allure Report with Selenium and JUnit4. In this tutorial, I will explain how to Integrate Allure Report with Selenium and JUnit5.

Pre-Requisite

  1. Java 11 installed
  2. Maven installed
  3. Eclipse or IntelliJ installed

This framework consists of:

  1. Selenium – 3.141.59
  2. Java 11
  3. JUnit – 4.13.2
  4. Maven – 3.8.1
  5. Allure Report – 2.14.0
  6. Allure JUnit4 – 2.14.0

Implementation Steps

  1. Update Properties section in Maven pom.xml
  2. Add Selenium, JUnit5 and Allure-JUnit5 dependencies in POM.xml
  3. Update Build Section of pom.xml in Allure Report Project.
  4. Create Pages and Test Code for the pages
  5. Run the Test and Generate Allure Report

Structure of Project

Step 1 – Update Properties section in Maven pom.xml

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>11</java.version>
    <selenium.version>3.141.59</selenium.version> 
    <junit.jupiter.version>5.8.0-M1</junit.jupiter.version>
    <junit.platform.version>1.8.0-M1</junit.platform.version>
    <allure.maven.version>2.10.0</allure.maven.version>
    <allure.junit5.version>2.14.0</allure.junit5.version>
    <maven.surefire.plugin.version>3.0.0-M3</maven.surefire.plugin.version>
    <maven.compiler.plugin.version>3.8.1</maven.compiler.plugin.version>
    <aspectj.version>1.9.6</aspectj.version>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

Step 2 – Add Selenium, JUnit5 and Allure-JUnit5 dependencies in POM.xml

<dependencies>
  
      <!--Selenium Dependency-->
      <dependency>
          <groupId>org.seleniumhq.selenium</groupId>
          <artifactId>selenium-java</artifactId>
          <version>${selenium.version}</version>
       </dependency>
  
     <!--JUNIT 5 Dependencies-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.jupiter.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.jupiter.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-engine</artifactId>
            <version>${junit.platform.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <version>${junit.platform.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-runner</artifactId>
            <version>${junit.platform.version}</version>
        </dependency>
        
        <!--Allure Reporting Dependencies-->
        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-junit5</artifactId>
            <version>${allure.junit5.version}</version>
        </dependency>
        
  </dependencies>

Step 3 – Update Build Section of pom.xml in Allure Report Project

<build>
        <plugins>
        <plugin>
               
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven.surefire.plugin.version}</version>
                <configuration>
                <testFailureIgnore>false</testFailureIgnore>
                        <argLine>
                            -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                        </argLine>
                    <systemProperties>
                        <property>
                            <name>junit.jupiter.extensions.autodetection.enabled</name>
                            <value>true</value>
                        </property>
                    </systemProperties>
                </configuration>
                
                <dependencies>
                   
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjweaver</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
                
            </plugin>
            <plugin>
                <groupId>io.qameta.allure</groupId>
                <artifactId>allure-maven</artifactId>
                <version>${allure.maven.version}</version>
                <configuration>
                    <reportVersion>2.4.1</reportVersion>
                </configuration>
            </plugin>
      </plugins>
  </build>

Step 4 – Create Pages and Test Code for the pages

Below is the sample project which uses Selenium and JUnit4 which is used to generate an Allure Report.

We have 2 pages. Below is the code for Login Page which contains all the web elements and methods related to that web elements.

public class LoginPage {

	WebDriver driver;

	By userName = By.name("txtUsername");

	By password = By.name("txtPassword");

	By titleText = By.id("logInPanelHeading");

	By login = By.id("btnLogin");

	By errorMessage = By.id("spanMessage");

	public LoginPage(WebDriver driver) {
		this.driver = driver;
	}

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

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

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

	@Step("Verify title of Login Page")
	public void verifyPageTitle() {
		String loginPageTitle = driver.findElement(titleText).getText();
		assertTrue(loginPageTitle.contains("LOGIN Panel"));
	}

	/* Failed Test */
	@Step("Verify error message when invalid credentail is provided")
	public void verifyErrorMessage() {
		String invalidCredentialErrorMessage = driver.findElement(errorMessage).getText();
		assertTrue(invalidCredentialErrorMessage.contains("Incorrect Credentials"));
	}

	@Step("Enter username and password")
	public void login(String strUserName, String strPasword) {

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

		// Fill password
		this.setPassword(strPasword);

		// Click Login button
		this.clickLogin();

	}
}

assertTrue() is imported from below JUnit package for assertion.

import static org.junit.jupiter.api.Assertions.assertTrue;

DashboardPage.java

public class DashboardPage {

	WebDriver driver;

	By dashboardPageTitle = By.id("welcome");

	By assignLeaveOption = By.cssSelector(
			"#dashboard-quick-launch-panel-menu_holder > table > tbody > tr > td:nth-child(1) > div > a > span");

	By leaveListOption = By.cssSelector(
			"#dashboard-quick-launch-panel-menu_holder > table > tbody > tr > td:nth-child(2) > div > a > span");

	By timesheetsOption = By.cssSelector(
			"#dashboard-quick-launch-panel-menu_holder > table > tbody > tr > td:nth-child(3) > div > a > span");

	By applyLeaveOption = By.cssSelector(
			"#dashboard-quick-launch-panel-menu_holder > table > tbody > tr > td:nth-child(4) > div > a > span");

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

	}

	@Step("Verify title of Dashboard page")
	public void verifyDashboardPageTitle() {
		String DashboardPageTitle = driver.findElement(dashboardPageTitle).getText();
		assertTrue(DashboardPageTitle.contains("Welcome"));
	}

	@Step("Verify Assign Leave Quick Launch Options on Dashboard page")
	public void verifyAssignLeaveOption() {
		String QuickLaunchOptions = driver.findElement(assignLeaveOption).getText();
		assertTrue(QuickLaunchOptions.contains("Assign Leave"));
	}

	@Step("Verify Leave List Quick Launch Options on Dashboard page")
	public void verifyLeaveListOption() {
		String LeaveListQuickLaunchOption = driver.findElement(leaveListOption).getText();
		assertTrue(LeaveListQuickLaunchOption.contains("Leave List"));
	}

	@Step("Verify Assign Leave Quick Launch Options on Dashboard page")
	public void verifytimesheetsOption() {
		String timesheetsOptionQuickLaunchOption = driver.findElement(timesheetsOption).getText();
		assertTrue(timesheetsOptionQuickLaunchOption.contains("Timesheets"));
	}

	@Step("Verify Leave List Quick Launch Options on Dashboard page")
	public void verifyApplyLeaveOption() {
		String applyLeaveQuickLaunchOptions = driver.findElement(applyLeaveOption).getText();
		assertTrue(applyLeaveQuickLaunchOptions.contains("Apply Leave"));
	}

}


Test Classes related to various Pages

BaseTest.java

public class BaseTest {

	public static WebDriver driver;
	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Step("Start the application")
	@BeforeEach
	public void setup() {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	@Step("Stop the application")
	@AfterEach
	public void close() {
		driver.close();
	}
}

@BeforeEach is used to signal that the annotated method should beexecuted before each @Test, @RepeatedTest, @ParameterizedTest, @TestFactory,and @TestTemplate method in the current test class. It is imported from:-

import org.junit.jupiter.api.BeforeEach;

AfterEach is used to signal that the annotated method should beexecuted after each @Test, @RepeatedTest, @ParameterizedTest, @TestFactory,and @TestTemplate method in the current test class. It is imported from:-

import org.junit.jupiter.api.AfterEach;

LoginTests.java

@Epic("Web Application Regression Testing using JUnit5")
@Feature("Login Page Tests")
public class LoginTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Severity(SeverityLevel.NORMAL)
	@Test
	@Description("Test Description : Verify the title of Login Page")
	@Story("Title of Login Page")
	public void verifyLoginPage() {

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

		// Verify login page text
		objLogin.verifyPageTitle();
	}

	@Severity(SeverityLevel.BLOCKER)
	@Test
	@Description("Test Description : Login Test with invalid credentials")
	@Story("Unsuccessful Login to Application")
	public void invalidCredentialTest() {

		// Create Login Page object
		objLogin = new LoginPage(driver);
		objLogin.login("test", "test123");

		// Verify login page text
		objLogin.verifyErrorMessage();

	}

}

DashboardTests.java

package com.example.Junit5AllureReportDemo.tests;

import org.junit.jupiter.api.Test;

import com.example.Junit5AllureReportDemo.pages.DashboardPage;
import com.example.Junit5AllureReportDemo.pages.LoginPage;

import io.qameta.allure.Description;
import io.qameta.allure.Epic;
import io.qameta.allure.Feature;
import io.qameta.allure.Severity;
import io.qameta.allure.SeverityLevel;
import io.qameta.allure.Story;

@Epic("Web Application Regression Testing using JUnit5")
@Feature("Dashboard Page Tests")
public class DashboardTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Severity(SeverityLevel.BLOCKER)
	@Test
	@Description("Test Description : Verify title of Dashboard page")
	@Story("Title of Dashboard Page")
	public void dashboardTitleTest() {

		objLogin = new LoginPage(driver);

		// login to application
		objLogin.login("Admin", "admin123");

		// go the dashboard page
		objDashboardPage = new DashboardPage(driver);

		objDashboardPage.verifyDashboardPageTitle();

	}

	@Severity(SeverityLevel.BLOCKER)
	@Test
	@Description("Test Description : Verify Assign Leave Option in Quick Link Menu")
	@Story("Validation of Assign Leave Option")
	public void assignLeaveOptionTest() {

		objLogin = new LoginPage(driver);

		// login to application
		objLogin.login("Admin", "admin123");

		// go the dashboard page
		objDashboardPage = new DashboardPage(driver);

		objDashboardPage.verifyAssignLeaveOption();

	}

	@Severity(SeverityLevel.BLOCKER)
	@Test
	@Description("Test Description : Verify Apply Leave Option in Quick Link Menu")
	@Story("Validation of Apply Leave Option")
	public void applyLeaveOptionTest() {

		objLogin = new LoginPage(driver);

		// login to application
		objLogin.login("Admin", "admin123");

		// go the dashboard page
		objDashboardPage = new DashboardPage(driver);

		objDashboardPage.verifyApplyLeaveOption();

	}

	@Severity(SeverityLevel.BLOCKER)
	@Test
	@Description("Test Description : Verify Leave List Option in Quick Link Menu")
	@Story("Validation of Leave List Option")
	public void leaveListOptionTest() {

		objLogin = new LoginPage(driver);

		// login to application
		objLogin.login("Admin", "admin123");

		// go the dashboard page
		objDashboardPage = new DashboardPage(driver);

		objDashboardPage.verifyLeaveListOption();

	}

	@Severity(SeverityLevel.BLOCKER)
	@Test
	@Description("Test Description : Verify Timesheets Option in Quick Link Menu")
	@Story("Validation of Timesheets Option")
	public void timesheetsOptionTest() {

		objLogin = new LoginPage(driver);

		// login to application
		objLogin.login("Admin", "admin123");

		// go the dashboard page
		objDashboardPage = new DashboardPage(driver);

		objDashboardPage.verifyTimesheetsOption();

	}

}

Step 5 – Run the Test and Generate Allure Report

To run the tests, use the below command

mvn clean test

In the below image, we can see that one test is failed and six passed out of seven tests.

This will create allure-results folder with all the test report. These files will be use to generate Allure Report.

To create Allure Report, use the below command

allure serve

This will generate the beautiful Allure Test Report as shown below.

Allure Report Dashboard

Categories in Allure Report

Categories tab gives you the way to create custom defects classification to apply for test results. There are two categories of defects – Product Defects (failed tests) and Test Defects (broken tests).

Suites in Allure Report

On the Suites tab a standard structural representation of executed tests, grouped by suites and classes can be found.

Graphs in Allure Report

Graphs allow you to see different statistics collected from the test data: statuses breakdown or severity and duration diagrams.

Timeline in Allure Report

Timeline tab visualizes retrospective of tests execution, allure adaptors collect precise timings of tests, and here on this tab they are arranged accordingly to their sequential or parallel timing structure.

Behaviors of Allure Report

This tab groups test results according to Epic, Feature and Story tags.

Packages in Allure Report

Packages tab represents a tree-like layout of test results, grouped by different packages.

Integration of Allure Report with Selenium and JUnit4

HOME

In the previous tutorial, I have explained the Integration of the Allure Report with Selenium and TestNG. In this tutorial, I will explain how to Integrate Allure Report with Selenium and JUnit4.

What is Allure Framework?

Allure is an open-source framework designed to create interactive and comprehensive test report by Yandex QA Team.

Below example covers the implementation of Allure Reports in Selenium using JUnit4, Java and Maven.

Pre-Requisite

  1. Java 11 installed
  2. Maven installed
  3. Eclipse or IntelliJ installed

This framework consists of:

  1. Selenium – 3.141.59
  2. Java 11
  3. JUnit – 4.13.2
  4. Maven – 3.8.1
  5. Allure Report – 2.14.0
  6. Allure JUnit4 – 2.14.0

Implementation Steps

  1. Update Properties section in Maven pom.xml
  2. Add Selenium, JUnit4 and Allure-JUnit4 dependencies in POM.xml
  3. Update Build Section of pom.xml in Allure Report Project.
  4. Create Pages and Test Code for the pages
  5. Run the Test and Generate Allure Report

Structure of Project

Step 1 – Update Properties section in Maven pom.xml

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <selenium.version>3.141.59</selenium.version>
    <junit.version>4.13.2</junit.version>
    <allure.junit4.version>2.14.0</allure.junit4.version>
    <maven.compiler.plugin.version>3.5.1</maven.compiler.plugin.version>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
    <aspectj.version>1.9.6</aspectj.version>
    <maven-surefire-plugin-version>3.0.0-M5</maven-surefire-plugin-version>
  </properties>

Step 2 – Add Selenium, JUnit4 and Allure-JUnit4 dependencies in POM.xml

<dependencies>
   <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>${selenium.version}</version>
    </dependency>
    
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    
     <dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-junit4</artifactId>
        <version>${allure.junit4.version}</version>
        <scope>test</scope>
    </dependency>   
  </dependencies>

Step 3 – Update Build Section of pom.xml in Allure Report Project

<build>
       
       <plugins>
   <!-- Compiler plug-in -->
  
           <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source> <!--For JAVA 8 use 1.8-->
                    <target>${maven.compiler.target}</target> <!--For JAVA 8 use 1.8-->
                </configuration>
            </plugin>
            
     <!-- Added Surefire Plugin configuration to execute tests -->       
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven-surefire-plugin-version}</version>
            <configuration>
                <testFailureIgnore>false</testFailureIgnore>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                </argLine>
                <properties>
                    <property>
                        <name>listener</name>
                        <value>io.qameta.allure.junit4.AllureJunit4</value>
                    </property>
                </properties>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
        </plugin>
      </plugins>
  </build>

Step 4 – Create Pages and Test Code for the pages

Below is the sample project which uses Selenium and JUnit4 which is used to generate an Allure Report.

We have 2 pages. Below is the code for Login Page which contains all the web elements and methods related to that web elements.

public class LoginPage {

	WebDriver driver;

	By userName = By.name("txtUsername");

	By password = By.name("txtPassword");

	By titleText = By.id("logInPanelHeading");

	By login = By.id("btnLogin");

	By errorMessage = By.id("spanMessage");

	public LoginPage(WebDriver driver) {
		this.driver = driver;
	}

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

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

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

	@Step("Verify title of Login Page")
	public void verifyPageTitle() {
		String loginPageTitle = driver.findElement(titleText).getText();
		Assert.assertTrue(loginPageTitle.contains("LOGIN Panel"));
	}

	/* Failed Test */
	@Step("Verify error message when invalid credentail is provided")
	public void verifyErrorMessage() {
		String invalidCredentialErrorMessage = driver.findElement(errorMessage).getText();
		Assert.assertTrue(invalidCredentialErrorMessage.contains("Incorrect Credentials"));
	}

	@Step("Enter username and password")
	public void login(String strUserName, String strPasword) {

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

		// Fill password
		this.setPassword(strPasword);

		// Click Login button
		this.clickLogin();

	}
}

DashboardPage.java

public class DashboardPage {

	WebDriver driver;

	By dashboardPageTitle = By.id("welcome");

	By options = By.cssSelector(
			"#dashboard-quick-launch-panel-menu_holder > table > tbody > tr > td:nth-child(1) > div > a > span");

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

	}

	@Step("Verify title of Dashboard page")
	public void verifyDashboardPageTitle() {
		String DashboardPageTitle = driver.findElement(dashboardPageTitle).getText();
		Assert.assertTrue(DashboardPageTitle.contains("Welcome"));
	}

	@Step("Verify Quick Launch Options on Dashboard page")
	public void verifyQuickLaunchOptions() {
		String QuickLaunchOptions = driver.findElement(options).getText();
		Assert.assertTrue(QuickLaunchOptions.contains("Assign Leave"));
	}

}

Test Classes related to various Pages

BaseTest.java

public class BaseTest {

	public static WebDriver driver;
	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Step("Start the application")
	@Before
	public void setup() {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	@Step("Stop the application")
	@After
	public void close() {
		driver.close();
	}
}

LoginTests.java

@Epic("Web Application Regression Testing using JUnit4")
@Feature("Login Page Tests")
@Listeners(TestExecutionListener.class)
public class LoginTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Severity(SeverityLevel.NORMAL)
	@Test(priority = 0, description = "Verify Login Page")
	@Description("Test Description : Verify the title of Login Page")
	@Story("Title of Login Page")
	public void verifyLoginPage() {

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

		// Verify login page text
		objLogin.verifyPageTitle();
	}

	@Severity(SeverityLevel.BLOCKER)
	@Test(priority = 1, description = "Login with invalid username and password")
	@Description("Test Description : Login Test with invalid credentials")
	@Story("Unsuccessful Login to Application")
	public void invalidCredentialTest() {

		// Create Login Page object
		objLogin = new LoginPage(driver);
		objLogin.login("test", "test123");

		// Verify login page text
		objLogin.verifyErrorMessage();

	}

}

DashboardTests.java

@Epic("Web Application Regression Testing using JUnit4")
@Feature("Dashboard Page Tests")
public class DashboardTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Severity(SeverityLevel.BLOCKER)
	@Test
	@Description("Test Description : After successful login to application opens Dashboard page")
	@Story("Successful login of application opens Dashboard Page")

	public void DasboardTest() {

		objLogin = new LoginPage(driver);

		// login to application
		objLogin.login("Admin", "admin123");

		// go the dashboard page
		objDashboardPage = new DashboardPage(driver);

		// Verify dashboard page
		objDashboardPage.verifyQuickLaunchOptions();

	}

}

Step 5 – Run the Test and Generate Allure Report

To run the tests, use the below command

mvn clean test

In the below image, we can see that one test is failed and two passed out of three tests.

This will create allure-results folder with all the test report. These files will be use to generate Allure Report.

To create Allure Report, use the below command

allure serve

This will generate the beautiful Allure Test Report as shown below.

Allure Report Dashboard

Overview page hosts several default widgets representing basic characteristics of your project and test environment.

  1. Statistics – overall report statistics.
  2. Launches – if this report represents several test launches, statistics per launch will be shown here.
  3. Behaviors – information on results aggregated according to stories and features.
  4. Executors – information on test executors that were used to run the tests.
  5. History Trend – if tests accumulated some historical data, it’s trend will be calculated and shown on the graph.
  6. Environment – information on test environment.

Categories in Allure Report

Categories tab gives you the way to create custom defects classification to apply for test results. There are two categories of defects – Product Defects (failed tests) and Test Defects (broken tests).

Suites in Allure Report

On the Suites tab a standard structural representation of executed tests, grouped by suites and classes can be found.

Graphs in Allure Report

Graphs allow you to see different statistics collected from the test data: statuses breakdown or severity and duration diagrams.

Timeline in Allure Report

Timeline tab visualizes retrospective of tests execution, allure adaptors collect precise timings of tests, and here on this tab they are arranged accordingly to their sequential or parallel timing structure.

Behaviors of Allure Report

This tab groups test results according to Epic, Feature and Story tags.

Packages in Allure Report

Packages tab represents a tree-like layout of test results, grouped by different packages.

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!!

Page Object Model with Page Factory in Selenium

HOME

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.

The benefit is that if there is any change in the UI for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently all changes to support that new UI are located in one place.

The Page Object Design Pattern provides the following advantages:

1. Readable – There is a clean separation between test code and page specific code such as locators and methods.

2. Maintainability  -In this model, separate classes are created for different pages of a web application like login page, the home page, employee detail page, change password page, etc. So, if there is any change in any element of a website then we only need to make changes in one class, and not in all classes.

3. Reusable – If multiple test scripts use the same web elements, then we need not write code to handle the web element in every test script. Placing it in a separate page class makes it reusable by making it accessible by any test script.

4. Easy project Structure – Its project structure is quite easy and understandable.

5. PageFactory – It can use PageFactory in the page object model in order to initialize the web element and store elements in the cache.

In case there are lots of web elements on a page, then the object repository class for a page can be separated from the class that includes methods for the corresponding page.

 Example: If the New Customer page has many input fields. In that case, there can be 2 different classes. One class called NewCustomerObjects.java that forms the object repository for the UI elements on the register accounts page.

A separate class file NewCustomerMethods.java extending or inheriting NewCustomerObjects that includes all the methods performing different actions on the page could be created.

Consider the below script to login to an application and navigate to home page.

This is a small script. Therefore, script maintenance and readability looks very easy.

Imagine there are 50 different tests present in this script. In that case, the readability of the script decreases as well as maintenance become very difficult.

Scenario

  1. Launch the Firefox browser.
  2. The demo website opens in the browser.
  3. Verify the Login Page
  4. Enter username and Password and login to the demo site.
  5. Verify the home page.
  6. Close the browser.
package PageObjectModel;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class NonPOMExample {

     WebDriver driver;

     @BeforeTest
     public void setup() {

           System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
           driver = new FirefoxDriver();
           driver.manage().window().maximize();
           driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
           driver.get("https://opensource-demo.orangehrmlive.com/");
     }

     @Test(priority = 0)
     public void Login() {
           String pageTitle = driver.findElement(By.id("logInPanelHeading")).getText();
           Assert.assertTrue(pageTitle.contains("LOGIN Panel"));
     }

     @Test(priority = 1)
     public void HomePage() {

           driver.findElement(By.name("txtUsername")).sendKeys("Admin");
           driver.findElement(By.name("txtPassword")).sendKeys("admin123");
           driver.findElement(By.id("btnLogin")).submit();
           String homePageText = driver.findElement(By.id("welcome")).getText();
           Assert.assertTrue(homePageText.contains("Welcome"));
     }

     @AfterTest
     public void close() {
           driver.close();
     } 
}

What Is Pagefactory?

PageFactory is a way of implementing the “Page Object Model”. Here, we follow the principle of separation of Page Object Repository and Test Methods. It is an inbuilt concept of Page Object Model which is very optimized.

1. The annotation @FindBy is used in Pagefactory to identify an element while POM without Pagefactory uses the driver.findElement() method to locate an element.

2. The second statement for Pagefactory after @FindBy is assigning an <element name> of type WebElement class that works exactly similar to the assignment of an element name of type WebElement class as a return type of the method driver.findElement() that is used in usual POM (userName in this example).

Non POM

driver.findElement(By.name("txtUsername"));

POM

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

3. Below is a code snippet of non PageFactory Mode to set Firefox driver path. A WebDriver instance is created with the name driver and the FirefoxDriver is assigned to the ‘driver’.  The same driver object is then used to launch the demo website, locate the webelements and to perform various operations

Basically, here the driver instance is created initially and every web element is freshly initialized each time when there is a call to that web element using driver.findElement() or driver.findElements().

 System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
          driver = new FirefoxDriver();
           driver.manage().window().maximize();
           driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
           driver.get("https://opensource-demo.orangehrmlive.com/");

But with POM with PageFactory approach, all the elements are initialized with initElements() without explicitly initializing each web element.

The initElements is a static method of PageFactory class which is used to initialize all the web elements located by @FindBy annotation. Thus, instantiating the Page classes easily. It is used to initialize the WebElements declared, using driver instance from the main class. In other words, WebElements are created using the driver instance. 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);
     }

Steps To Create POM With Page Factory Real-Time Example

Step 1 – Create a Maven Project

Click here to know How to create a Maven project

Step 2 – Add dependencies to the pom.xml

<dependencies>
   
   <!-- 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>
     
    <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>7.4.0</version>
      <scope>test</scope>
    </dependency>   
     
</dependencies>

Step 3 – Create a Java Class for each page:

In this example, we will access 2 web pages, “Login” and “Home” pages.

Hence, we will create 2 Java classes in Page Layer  –  Login.java and HomePage.java

3.1. Define WebElements as variables using Annotation @FindBy:

We would be interacting with:

  • Message on Login Page, Username, Password, Login button field on the Login Page.
  • Successful message on the Home Page

For Example: If we are going to identify the Username using attribute name, then its variable declaration is

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

3.2 Create methods for actions performed on WebElements.

Below actions are performed on WebElements in Login Page:

  • Get Text on Login Page
  • Type action on the Username field.
  • Type action in the Password field.
  • Click action on the Login Button

Note: A constructor has to be created in each of the class in the Page Layer, in order to get the driver instance from the Main class in Test Layer and also to initialize WebElements(Page Objects) declared in the page class using PageFactory.InitElement().

Login Page

package PageObjectModel;

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 strPasword) {

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

           // Fill password
           this.setPassword(strPasword);

           // Click Login button
           this.clickLogin();
     }
}

HomePage. java

package PageObjectModel;

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();
     }
}

Step 4 –  Create test class for the tests of these pages – POMTest

POMTest.java

package PageObjectModel;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class POMTest {

     WebDriver driver;
     Login objLogin;
     HomePage objHomePage;
 
     @BeforeTest
     public void setup() {
          System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
           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
      *
      */

     @Test(priority = 0)
     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"));
     }

     @Test(priority = 1)
     public void HomeTest() {

           // login to application
           objLogin.login("Admin", "admin123");

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

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

     @AfterTest
     public void close() {
           driver.close();
     }
}

Step 5 – To run the test, right click and select as Run As and then select TestNG Test.

Step 6 – Create TestNG.xml

You can add TestNG.xml and run the tests from there also.

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "PageObjectModel">
  <test name = "PageObjectModel Tests">
    <classes>
          <class name = "com.example.pageobjectmodel.tests.POMTest"/>
     </classes>  
   </test>
</suite>

Step 7 – Run the tests from TestNG.xml

Right click on TestNG.xml and select Run As TestNG Suite.

The execution status looks like as shown below.

Step 8 -TestNG Report Generation

Once the execution is finished, refresh the project. It will create a test-output folder containing various reports generated by TestNG. Below is the screenshot of the report folder.

Image of Index.html report

Image of emailable-report.html

Selenium Tutorials

 HOME

                 

Selenium is not a single automation Tool like QTP, but it is basically a suite of software’s or set of JAR files to automate web browser across various browsers. Selenium is used by many companies, but few to mention are Netflix, Google, HubSpot, Fitbit, and more.

  Selenium – Introduction, Installation, Test Script
Chapter 1 Introduction to Selenium Automation Tool
Chapter 2 How to Download & Install Java JDK 11 in Windows
Chapter 3 How to Download and Install Eclipse IDE
Chapter 4 How to install IntelliJ on Windows
Chapter 5 How to Download & Install Selenium WebDriver 
Chapter 6  How to create first Selenium WebDriver Script using Java

Selenium – Basic & Advance concepts of WebDriver

 Locators in Selenium

 Chapter 1 How to Locate Elements in Chrome, Firefox and IE Browsers for creating Selenium Scripts
Chapter 2 Locators in Selenium – Locate by ID, ClassName,  Name, TagName,  LinkText, PartialLinkText
Chapter 3 Dynamic XPath  in Selenium WebDriver
Chapter 4 CSS Selector in Selenium WebDriver

WebElements in Selenium

Chapter 1 Difference between FindElement and FindElements in WebDriver
Chapter 2 Difference between getText() and getAttribute() method in WebDriver
Chapter 3 WebDriver Browser Commands – get,  getTitle, getCurrentUrl, getPageSource, getClass, close, quit in WebDriver
Chapter 4 WebDriver Navigation Commands – Navigate, Forward, Back, Refresh in  WebDriver
Chapter 5 Selenium Form WebElement Commands – Sendkeys, Clear, Click,Submit
Chapter 6 How to automate selecting Checkbox and Radio Buttons in WebDriver
Chapter 7 How to Select value from Drop down list or perform Multiple Selection  Operations in WebDriver
Chapter 8 How to get all options in a DropDown list in WebDriver
Chapter 9 How to automate Radio Button in WebDriver
Chapter 10 How to automate BootStrap DropDown using WebDriver
Chapter 11 Implicit, Explicit and Fluent Wait in WebDriver
Chapter 12 What is Fluent Wait in Selenium WebDriver
Chapter 13 Switch Window Commands in Selenium WebDriver
Chapter 14 How to handle Alerts in Selenium WebDriver
Chapter 15 How to handle Dynamic Web Tables using Selenium WebDriver
Chapter 16 How to get all the values from a Dynamic Table in Selenium WebDriver 

Advance Selenium

Chapter 1 JavaScript and JavaScript Executor in Selenium
Chapter 2 Execute JavaScript with executeScript() Method in Selenium
Chapter 3 Execute JavaScript with executeAsyncScript() Method in Selenium
Chapter 4 Actions Class in Selenium WebDriver
Chapter 5 Drag and Drop action in Selenium WebDriver
Chapter 6 How to Capture Screenshot in Selenium Webdriver
Chapter 7 How to use FileHandler Class to take Screenshot in Selenium WebDriver
Chapter 8  How to Upload a File using Selenium Webdriver
Chapter 9 How to download and install Apache POI
Chapter 10 How to read data from Excel in Java
Chapter 11 How to write data in Excel in Java
Chapter 12 How to update existing excel in Java

Frameworks

Chapter 1 Page Object Model with Page Factory in Selenium
Chapter 2 Page Object Model with Selenium and Cucumber
Chapter 3 Integration of Cucumber with Selenium and JUnit
Chapter 4 Integration of Cucumber with Selenium and TestNG

How to Upload a File using Selenium Webdriver

HOME

We often face the problem where we have to upload a file in Web Application. This can be easily achieved in Selenium. We are using sendKeys() method to set the value of the file to upload. In this tutorial, will see how to upload a document in Selenium.

Let’s explain this with the help of an example.

1) Launch new Browser and open “https://demoqa.com/upload-download&#8221;
2) Locate the button “Choose File” by using xpath
3) Use sendkeys() to upload the file
4) After uploading the file, verify the message displayed on web page
5) Close the browser

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class UploadDemo {
    public static void main(String args[]) {
 
        System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\webdrivers\\window\\chromedriver.exe");
 
        // Initiate Chrome browser
        WebDriver driver = new ChromeDriver();
        driver.get("https://demoqa.com/upload-download");
 
        // Maximize the browser
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 
        // Locating upload button
        WebElement upload = driver.findElement(By.id("uploadFile"));
                        
        //Upload the file
        upload.sendKeys("C:\\Users\\Vibha\\Desktop\\SeleniumTest.txt");
 
        String Message = driver.findElement(By.id("uploadedFilePath")).getText();
        System.out.println("Message is :" + Message);
 
        // close the browser
        driver.close();
     }
}

The web page after uploading the file looks something like as shown below

Screenshot of Failed Test Cases in Selenium WebDriver

HOME

In the previous tutorials, I have explained how we can take screenshots in Selenium using FileUtils or FileHandler. In this tutorial, I will explain how to capture screenshots of Failed Test Cases in Selenium.

We are going to use TestNG to capture screenshot of failed test cases.

We will be using below mentioned features of TestNG

1) ITestResult – This  Interface will provide us the result of test case execution. @AfterMethod method can declare a parameter of type ITestResult, which will reflect the result of the test method that was just run.

2) @AfterMethod – The annotated method will be run after each test method. Any @AfterMethod can declare a parameter of type java.lang.reflect.Method. This parameter will receive the test method that will be called once this after the method as run.

3) result.getName() – will return name of test case so that screenshot name will be same as test case name

4) @BeforeTest – The annotated method will be run before any test method belonging to the classes inside the tag is run.

5) @AfterTest – The annotated method will be run after all the test methods belonging to the classes inside the tag have run.

We are executing 2 test cases. One of the Test Case will pass and another will fail. This program will only capture the screenshot of failed test case, not the passed one as we have used condition

if (ITestResult.FAILURE == result.getStatus())

Let see this as a program. 

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
 
public class ScreenshotFailedCases {
    static WebDriver driver;
 
    @BeforeTest
    public static void init() {
        System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
 
        // Initiate Firefox browser
        driver = new FirefoxDriver();
 
        // Maximize the browser
        driver.manage().window().maximize();
 
        // Pass application url
        driver.get("https://duckduckgo.com/");
        System.out.println("BeforeTest");
    }
 
    @Test
    public void captureCorrectScreenMethod() throws Exception {
        String Text = driver.findElement(By.xpath("//*[@id='logo_homepage_link']")).getText();
        // Verify the text on the landing page
        Assert.assertTrue(Text.contains("About DuckDuckGo"));
    }
 
    @Test
    public void captureIncorrectScreenMethod() throws Exception {
                        
		// Fail test by using incorrect XPath to find the search box
        driver.findElement(By.xpath("//*[@name='qe']")).sendKeys("agile");
    }
 
    @AfterTest
    public static void exit() {
                        
		// Close the WebPage
        driver.quit();
    }
 
    // AfterMethod annotation - This method executes after every test execution
    @AfterMethod
    public void screenShot(ITestResult result) {
 
        // ITestResult.FAILURE is equals to result.getStatus then it enter into
        // if condition
                        
	if (ITestResult.FAILURE == result.getStatus()) {
            try {
                    
		         // To create reference of TakesScreenshot
                 TakesScreenshot screenshot = (TakesScreenshot) driver;
 
                 // Call method to capture screenshot
                 File src = screenshot.getScreenshotAs(OutputType.FILE);
 
                 // Copy files to specific location result.getName() will 
                 // return  name of test case so that screenshot name will be same as test case name
                    
		   FileUtils.copyFile(src, new File("./Screenshots/" + result.getName() + System.currentTimeMillis() + ".png"));
                    System.out.println("Successfully captured a screenshot");
                } catch (Exception e) {
                    System.out.println("Exception while taking screenshot " + e.getMessage());
           }
        }
    }
}

A folder with name Screenshots is created and the screenshot is placed in that folder as you can see the image below

Execution Status as shown below

TestNG Report – Go to test-output folder and open emailable-report.html

How to use FileHandler Class to take Screenshot in Selenium WebDriver

 HOME

In the previous post, I have explained how to capture screenshots in Selenium using FileUtils. In this post, will see another way of capturing the screenshots in Selenium.

FileHandler is new Class in Selenium which help us to store screenshots, create directory and so on. You can get full documentation of FileHandler here

Step 1- Import the new package which is

import org.openqa.selenium.io.FileHandler;

Step 2 – To capture a screenshot in Selenium, we can make use of an interface, called TakesScreenshot. This method indicates the driver, that it can capture a screenshot and store it in different ways

TakesScreenshot ts = (TakesScreenshot) driver;

Step 3 – In order to capture screenshot and store it in a particular location, there is a method called “getScreenshotAs“, where OutputType defines the output type for a screenshot.

File source = ts.getScreenshotAs(OutputType.FILE);

Step 4- Call copy method of FileHandler Class which is static method and will ask two argument First is src and another is destination. Code will look like 

FileHandler.copy(source, new File("/Screenshots/SeleniumScreenshot" + System.currentTimeMillis() + ".png"));

Let’s see this in a Selenium program:-

import java.io.File;
 
import java.io.IOException; 
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.io.FileHandler;
 
public class ScreenshotExample {
      public static void main(String[] args) throws IOException {

            System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
            WebDriver driver = new FirefoxDriver();

            // Maximize the window
            driver.manage().window().maximize();
            driver.get("https://configureselenium.blogspot.com/");

            // Convert web driver object to TakeScreenshot
            TakesScreenshot ts = (TakesScreenshot) driver;

            // Call getScreenshotAs method to create image file
            File source = ts.getScreenshotAs(OutputType.FILE);

            // Copy file at destination
            FileHandler.copy(source, new File("./Screenshots/SeleniumScreenshot" + System.currentTimeMillis() + ".png"));
            System.out.println("the Screenshot is taken");

            // close the current browser
            driver.quit();
      } 
 
}

A folder with name “Screenshots” created and the screenshot placed in that folder as you can see the image below

The Screenshot looks like something as shown below