Planet Jaspersoft

July 15, 2022

Hi, 

Below piece of code verifies if the xml response has Text1 in it then performs Text1 tests else performs Text2 and Text3 tests respectively. 

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if( pm.response.text().has("Text1")){

console.log("Received : body contains Text1");

pm.test("Body contains Text1",() => {
pm.expect(pm.response.text()).to.include("Text1");
});

}else{

console.log(" Not Received : Text1 so verifying for Text2 and Text3");

pm.test("Body contains Text2",() => {
pm.expect(pm.response.text()).to.include("Text2");
});

pm.test("Body contains Text2",() => {
pm.expect(pm.response.text()).to.include("Text2");
});

}


July 15, 2022

Below command on node.js command line generates html report with date and time.  

newman run TestCollection.postman_collection.json  -e TestEnvironment.postman_environment.json -r htmlextra --reporter-htmlextra-export D:\posman\newman\TestCollectionReport_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%.html

Example:
D:/postman/newman/TestCollectionReport_20221507_1720.html


Tap on the below image for best view



July 15, 2022

July 6, 2022

Hi, In this post, we'll learn about how to integrate Cucumber with Selenium, TestNG and Maven.

This is as part of a project that we wanted to migrate the UI automation from Junit frame work to TestNG and we also wanted to upgrade to the latest versions of the dependencies. 

For the demo, we will use the HRM website. 
https://opensource-demo.orangehrmlive.com/index.php/auth/login
Username : Admin, Password: admin123 

Let's take the following use case of scenario's. 

Test Cases/Scenarios: 

Verify log-in page with valid credentials 
Display the size of quick launch elements Dashboard page/tab
Directory tab navigation from Dashboard page/tab
Verify Search button is displayed or not in Dictionary page/tab

In this framework, we will see the below technical implementations of Cucumber, Selenium and TestNG

Cucumber features: 

  • How to implement  data driven approach using DataTable object in Login scenario ? 
  • How to use Background keyword in feature files to to login for each scenario except for Login?
    (keep the tests independent of each other)
  • How to give Tags(single and multiple tags) in CucumberOptions in RunCucumberTest  class? 
  • How to use Cucumber Before and  After Hooks for each scenario ?
  • Online cucumber report 

Selenium features: 

  • Implicit wait with Duration of times 
  • Explicit wait with Duration of times
  • findElements , add elments to List<WebElement>, display the list elements, size of the list


TestNG and Maven features:

  • Assertions used in this demo are from TestNG framework. 
  • How to configure testng.xml file in pom.xml in the maven-surefire-plugin
  • How to run the cucumber scenarios from command line ? 

Let's begin! 

The first and foremost thing, I've come across is to create the proper maven project structure.
i.e., the usage of src/test/java and src/test/resources 
We can keep our source code in src/main/java and src/main/resources but in order to run the scenarios from maven command line, this cucumber-java-skeleton is recommended to keep the code in 
src/test/java and src/test/resources - at least for the RunnerTest classes so the maven sure fire plug-in identifies the code from test

Having walk-through above all,  here we start with what versions this writing consists of
  • cucumber-java 7.1.0
  • cucumber-testng 7.1.0
  • selenium 4.3.0
  • testng 7.1.0
  • maven-surefire-plugin 3.0.0-M7
  • maven-compiler-plugin 3.10.1
  • Maven installed in Windows is 3.8.6

Project Structure: 

Source code : GitHub or download this zip 

Watch, the no voice walk-through video tutorial on YouTube



Now, the steps: 

  • Download and install Cucumber plug-in in Eclipse from Market Place
  • Download and install TestNG plug-in in Eclipse from Market Place
  • Create a new Maven project (say : CucucumberTestNGSeleniumMavenCommandLine)
  • Add cucumber-java, cucumber-testng, testng and selenium dependencies in the pom.xml and etc. 
  • Add Maven compiler plugin, maven-surefire-plugin in pom.xml 
  • Create feature files(Gherkhin script) in src/test/resources folder
  • Write java, selenium, glue(step definitions), cucumber testng runner class in src/test/java folder
    • BasePage class for driver
    • Hooks class for cucumber Before and After hooks. 
    • Step Definition Or Glue Code for the feature files
    • Cucumber & TestNG runner class, RunCucumberTest.java
  •  Create testng.xml for the project and configure it in pom.xml
  •  Run Tests from TestNG Tests
  •  Run Tests from testng.xml
  •  Run Tests from command line
  •  Test results analysis from Cucumber report
  •  Test results analysis from TestNG report

Step 1: Download and install Cucumber plug-in in Eclipse from Market Place
Install the cucumber plug in from the market place. 

Step 2: Download and install TestNG plug-in in Eclipse from Market Place
Install the cucumber plug in from the market place. 

Step 3: Download and install TestNG plug-in in Eclipse from Market Place

Refer to the above image : Project Structure (It should be  a maven project)

Step 4: Add cucumber-java, cucumber-testng, testng and selenium dependencies in the pom.xml and etc.  and 

Step 5: Add Maven compiler plugin, maven-surefire-plugin in pom.xml 

Add the dependencies as shown in below pom.xml  
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Cucumber7-TestNG7-Selenium4-OrnageHRM-POC2</groupId>
<artifactId>Cucumber7-TestNG7-Selenium4-OrnageHRM-POC2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.1.0</version>

</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.1.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->

</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

Step 6: Create feature files(Gherkhin script) in src/test/resources folder

The following scenarios are verified in this demo. This demo is designed to login for each scenario so the login step is used as Background step in the Dashbaord.feature and Directory.feature. 

HRMLogin.feature
@HRMLogin
Feature: Login to HRM Application
I want to use this template for HRM Login page

@LoginValidCredentials
Scenario: LoginValidCredentials
Given User login to HRM application with UserName and Password
| Admin | admin123 |
Then User navigates to Dashboard page

  Dashboard.feature
@Dasbhoard
Feature: Dashboard page
I want to use this template for my Dashboard Page

Background:
Given User login to HRM application with UserName and Password
| Admin | admin123 |
@DashboardTabCountOfQuickLaunhElements
Scenario: DashboardTabCountOfQuickLaunhElements
Then User finds the list of quick launch elements

@DirectoryTabNavigationFromDashboardTab
Scenario: DirectoryTabNavigationFromDashboardTab
Then User clicks on Directory tab and verifies the navigation

Directory.feature
@Directory
Feature: Dashboard page
I want to use this template for my Directory Page

Background:
Given User login to HRM application with UserName and Password
| Admin | admin123 |

@DirectoryTabIsSearchButtonDisplayed
Scenario: DirectoryTabIsSearchButtonDisplayed
Then User is on Directory page
Then Is Search button displayed

Step 7: Write java, selenium, glue(step definitions), cucumber testng runner class in src/test/java folder

BasePage class for driver
Define the web driver in this call and use it as super class for the step definition classes or in the Hooks class. 

Hooks class for cucumber Before and After hooks. 
In the Before Hook, get the login page.
Since it is a repeated activity for each scenario, we keep it in this Hook which means that the code that we write in Before Hook is executed/called before the execution of each scenario.
We can do this in Background band in the feature files as well. 

Use Before Hook and Background wisely. 

Step Definition Or Glue Code for the feature files
Write the glude code or step definitions code for each scenario in the HRMLoginPage.java, Dashboard.java and Directory.java files. 
iWe can rename the method names to avoid lengthy names that are generated through Feature run. 

Cucumber & TestNG runner class, RunCucumberTest.java
Runner class should end with Test because maven doesn't identify the cucumber testng integration while executing from command line. 
We can take any name for the runner class but should end with Test, in this case it is : RunCucumberTest.java
RunCucumberTest class should extends AbstractTestNGCucumberTests . 
The latest version of the cucumber testng accept tags with and or not 
For example, below statement executes two scenaro @LoginValidCredentials and @DirectoryTabIsSearchButtonDisplayed

tags="@LoginValidCredentials and not @DashboardTabCountOfQuickLaunhElements 
and not @DirectoryTabNavigationFromDashboardTab 
or @DirectoryTabIsSearchButtonDisplayed",

BasePage.java
package com.sadakar.common;
import org.openqa.selenium.WebDriver;
public class BasePage {

public static WebDriver driver;

}

Hooks.java
package com.sadakar.common;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.After;
import io.cucumber.java.Before;

public class Hooks extends BasePage {

@Before
public static void setupDriver() throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login");
}

@After
public static void quitDriver() throws Exception {
driver.quit();
}

}

HRMLoginPage.java 
package com.sadakar.stepdefinitions;

import java.time.Duration;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;

import com.sadakar.common.BasePage;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
public class HRMLoginPage extends BasePage {


@Given("User login to HRM application with UserName and Password")
public void loginToHRMApp(io.cucumber.datatable.DataTable dataTable) {

List<List<String>> cells = dataTable.cells();
driver.findElement(By.xpath("//*[@id=\"txtUsername\"]")).sendKeys(cells.get(0).get(0));
driver.findElement(By.xpath("//*[@id=\"txtPassword\"]")).sendKeys(cells.get(0).get(1));
driver.findElement(By.id("btnLogin")).submit();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
}
@Then("User navigates to Dashboard page")
public void navigateToDashboardTab() {

WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"menu_dashboard_index\"]")));

WebElement dashboardLabel = driver.findElement(By.xpath("//*[@id=\"content\"]/div/div[1]/h1"));
Assert.assertTrue(dashboardLabel.isDisplayed());
}
}

DashboardPage.java
 
package com.sadakar.stepdefinitions;

import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.sadakar.common.BasePage;

import io.cucumber.java.en.Then;
public class DashboardPage extends BasePage {

@Then("User finds the list of quick launch elements")
public void listOfQuickLaunchElementsOnDashboardPage() {

// Adding table data of a row to WebElement List
List<WebElement> actualListOfQuickLaunchElements = driver
.findElements(By.xpath("//*[@id=\"dashboard-quick-launch-panel-menu_holder\"]/table/tbody/tr/td"));

// Display the table data of row from the WebElementList
for (WebElement ele : actualListOfQuickLaunchElements) {
System.out.println(ele.getText());
}

// Display the size of WebElement List
System.out.println("Size of Quick launch elements : " + actualListOfQuickLaunchElements.size());

}

@Then("User clicks on Directory tab and verifies the navigation")
public void navigateToDirectoryTabFromDashbaordTab() {

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.findElement(By.xpath("//*[@id=\"menu_directory_viewDirectory\"]")).click();
}

}

DirectoryPage.java
package com.sadakar.stepdefinitions;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;

import com.sadakar.common.BasePage;

import io.cucumber.java.en.Then;
public class DirectoryPage extends BasePage{

@Then("User is on Directory page")
public void directoryPage() {

driver.findElement(By.xpath("//*[@id=\"menu_directory_viewDirectory\"]")).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
}

@Then("Is Search button displayed")
public void isSearchButtonDisplayed() {

WebElement searchButton = driver.findElement(By.xpath("//*[@id=\"searchBtn\"]"));
Assert.assertTrue(searchButton.isDisplayed());
}



}

RunCucumberTest.java
package com.sadakar.testng.runner;

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
@CucumberOptions(


//tags="@LoginValidCredentials",
//tags="@DashboardTabCountOfQuickLaunhElements",
//tags="@DirectoryTabNavigationFromDashboardTab",
//tags="@DirectoryTabIsSearchButtonDisplayed",
tags="@LoginValidCredentials or @DashboardTabCountOfQuickLaunhElements or @DirectoryTabNavigationFromDashboardTab or @DirectoryTabIsSearchButtonDisplayed",

//tags="@LoginValidCredentials and not @DashboardTabCountOfQuickLaunhElements and not @DirectoryTabNavigationFromDashboardTab and not @DirectoryTabIsSearchButtonDisplayed",

features = "classpath:features", glue = {"com.sadakar.common", "com.sadakar.stepdefinitions",
"com.sadakar.testng.runner"},

plugin = { "pretty", "json:target/cucumber-reports/cucumber.json", "html:target/cucumber-reports/cucumberreport.html" },

monochrome = true)
public class RunCucumberTest extends AbstractTestNGCucumberTests {


}

Step 8: Create testng.xml for the project and configure it in pom.xml

Creating testng.xml is optional when we run the code from Eclipse TestNG
But, what if the code has to be deployed to a Automation server and in it the code has to be triggered. 
We use maven command line to trigger the tests. 
Create testng.xml file in the project root and give the Runner class name as shown in below. 
And, then in the pom.xml configure the testng.xml - go back to to pom.xml and look at the plug-in section. 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="com.sadakar.testng.runner.RunCucumberTest"/>
</classes>
</test>
</suite>

Step 9: Run Tests from TestNG Tests


[RemoteTestNG] detected TestNG version 7.0.1

@Dasbhoard @DashboardTabCountOfQuickLaunhElements
Scenario: DashboardTabCountOfQuickLaunhElements # features/Dashboard.feature:9
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Starting ChromeDriver 103.0.5060.53 (a1711811edd74ff1cf2150f36ffa3b0dae40b17f-refs/branch-heads/5060@{#853}) on port 50670
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jul 06, 2022 12:49:38 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected upstream dialect: W3C
Jul 06, 2022 12:49:38 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found exact CDP implementation for version 103
Given User login to HRM application with UserName and Password # com.sadakar.stepdefinitions.HRMLoginPage.loginToHRMApp(io.cucumber.datatable.DataTable)
| Admin | admin123 |
Assign Leave
Leave List
Timesheets
Apply Leave
My Leave
My Timesheet
Size of Quick launch elements : 6
Then User finds the list of quick launch elements # com.sadakar.stepdefinitions.DashboardPage.listOfQuickLaunchElementsOnDashboardPage()

@Dasbhoard @DirectoryTabNavigationFromDashboardTab
Scenario: DirectoryTabNavigationFromDashboardTab # features/Dashboard.feature:13
Starting ChromeDriver 103.0.5060.53 (a1711811edd74ff1cf2150f36ffa3b0dae40b17f-refs/branch-heads/5060@{#853}) on port 52607
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jul 06, 2022 12:49:51 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected upstream dialect: W3C
Jul 06, 2022 12:49:51 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found exact CDP implementation for version 103
Given User login to HRM application with UserName and Password # com.sadakar.stepdefinitions.HRMLoginPage.loginToHRMApp(io.cucumber.datatable.DataTable)
| Admin | admin123 |
Then User clicks on Directory tab and verifies the navigation # com.sadakar.stepdefinitions.DashboardPage.navigateToDirectoryTabFromDashbaordTab()

@Directory @DirectoryTabIsSearchButtonDisplayed
Scenario: DirectoryTabIsSearchButtonDisplayed # features/Directory.feature:10
Starting ChromeDriver 103.0.5060.53 (a1711811edd74ff1cf2150f36ffa3b0dae40b17f-refs/branch-heads/5060@{#853}) on port 64336
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jul 06, 2022 12:50:11 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected upstream dialect: W3C
Jul 06, 2022 12:50:11 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found exact CDP implementation for version 103
Given User login to HRM application with UserName and Password # com.sadakar.stepdefinitions.HRMLoginPage.loginToHRMApp(io.cucumber.datatable.DataTable)
| Admin | admin123 |
Then User is on Directory page # com.sadakar.stepdefinitions.DirectoryPage.directoryPage()
Then Is Search button displayed # com.sadakar.stepdefinitions.DirectoryPage.isSearchButtonDisplayed()

@HRMLogin @LoginValidCredentials
Scenario: LoginValidCredentials # features/HRMLogin.feature:6
Starting ChromeDriver 103.0.5060.53 (a1711811edd74ff1cf2150f36ffa3b0dae40b17f-refs/branch-heads/5060@{#853}) on port 56598
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jul 06, 2022 12:50:32 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected upstream dialect: W3C
Jul 06, 2022 12:50:32 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found exact CDP implementation for version 103
Given User login to HRM application with UserName and Password # com.sadakar.stepdefinitions.HRMLoginPage.loginToHRMApp(io.cucumber.datatable.DataTable)
| Admin | admin123 |
Then User navigates to Dashboard page # com.sadakar.stepdefinitions.HRMLoginPage.navigateToDashboardTab()
????????????????????????????????????????????????????????????????????????????
? View your Cucumber Report at: ?
? https://reports.cucumber.io/reports/bebe12f4-ffa5-46a1-a8e2-11ea5d3ef259 ?
? ?
? This report will self-destruct in 24h. ?
? Keep reports forever: https://reports.cucumber.io/profile ?
????????????????????????????????????????????????????????????????????????????PASSED: runScenario("DashboardTabCountOfQuickLaunhElements", "Optional[Dashboard page]")
Runs Cucumber Scenarios
PASSED: runScenario("DirectoryTabNavigationFromDashboardTab", "Optional[Dashboard page]")
Runs Cucumber Scenarios
PASSED: runScenario("DirectoryTabIsSearchButtonDisplayed", "Optional[Dashboard page]")
Runs Cucumber Scenarios
PASSED: runScenario("LoginValidCredentials", "Optional[Login to HRM Application]")
Runs Cucumber Scenarios

===============================================
Default test
Tests run: 4, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 4, Passes: 4, Failures: 0, Skips: 0
===============================================

Step 10:  Run Tests from testng.xml

Logs generated through running testng.xml are same as above in Eclipse.

Step 11: Run Tests from command line

On the command line navigate to the folder where the project is saved and then issue mvn test command. This command will run all the scenarios from the project. 

Below are few examples on how to run or negate specific scenarios from the command line. 

These are the tags used for 4 scenarios. 
//tags="@LoginValidCredentials",
//tags="@DashboardTabCountOfQuickLaunhElements",
//tags="@DirectoryTabNavigationFromDashboardTab",
//tags="@DirectoryTabIsSearchButtonDisplayed",

Below command by default runs all the scenarios, basically irrespective of what we specify in CucumberOptions in the runner class maven will override it and run all the scenarios.
mvn test 
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

 
To run all the scenarios by mentionting all the tags, we need to use or between scenarios.
mvn test -Dcucumber.filter.tags="@LoginValidCredentials or @DashboardTabCountOfQuickLaunhElements or @DirectoryTabNavigationFromDashboardTab or @DirectoryTabIsSearchButtonDisplayed"
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

 
This command runs only one particular scenario
mvn test -Dcucumber.filter.tags="@LoginValidCredentials"
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

This command runs two scenarios
mvn test -Dcucumber.filter.tags="@LoginValidCredentials or @DashboardTabCountOfQuickLaunhElements"
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

If we use and between two scenarios, none of the scenarios will be executed.
mvn test -Dcucumber.filter.tags="@LoginValidCredentials and @DashboardTabCountOfQuickLaunhElements"
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

To negate a command i.e., to not run a particular scenario use and not
For instance, to run a scenario and to not a run scenario use below format. 
mvn test -Dcucumber.filter.tags="@LoginValidCredentials and not @DashboardTabCountOfQuickLaunhElements"
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0





Step 12: Test results analysis from Cucumber report



Step 13: Test results analysis from TestNG report
emailable-report.html



index.html

Cheers! We are done integrating cucumber with selenium, testng and maven. 

I hope you find this article is helped! Keep an eye on this space for future updates. 

July 6, 2022

July 1, 2022

Hi

In this tutorial, we'll learn about how to integrate Cucumber with TestNG and Selenium. 

Go through this article if and only if to validate Login page scenario with one session and to validate all the remaining scenarios with another session 

There is another tutorial out on integrating cucumber with testng and selenium. In this, we create a new driver session for each scenario so the tests are idependent. 

Integration of Cucumber with Selenium and TestNG, Maven | end to end example using 7.1 dependencies



Test Strategy: 
Verify the OrangeHRM login page with valid credentials 
Verify the count of elements in Quick Launch panel in the Dashboard Tab/Page.
Verify the navigation to Directory Tab/Page from Dashboard Tab/Page 
Verify the existence of  Search button in the Directory Tab/Page


No Voice Video Tutorial (Walkthrough)

Click Me To Download ZIP archived Project

OR 

Clone the project from Github

Integration Approach: 
In this frame work, if we want to validate login page as well as other scenarios
we create one driver session for login validation and another driver session for remaining scenarios. 

That is, browser opens for twice - once for login validation  and second time for remaining scenarios validation. 
Execution of scenarios are independent of each other. 

We use BeforeAll hook of Cucumber framework to login into the application so all the scenarios except login scenario shares this driver session from it.

As we are including the validation of logging we quit the session of driver from BeforeAll since we are already logged into the app before all the scenarios run so login validation is not possible.

In the login step definitions we quit the session of the driver from hook and 
 initiate new driver session so login validation will be done 

After login validation is done driver is not quit so this session will be used by any other scenarios that runs randomly and after executing all the scenarios the driver quit from AfterAll hook. 


DISCLAIMER :
This is an experiment on how to avoid login for each scenario from various feature files as we normally use Background band in feature files for login purposes.
Adoption of this approach is one's own interest. 


Framework set-up consists of : 
1. Java 16 (Eclipse Build Path)
2. Cucumber Java 7.4.0 (pom.xml)
3. Cucumber TestNG 7.4.0 (pom.xml)
4. Selenium 4.3.0 (pom.xml)
5. Maven 3.8.1 (Embedded in Eclipse/Installed from Market Place)
   (To run the tests from command line install Apache Maven in Windows 10/11 - I've installed 3.8.6)

Steps to create the frame work: 
1. Download and install Cucumber plug-in in Eclipse from Market Place
2. Download and install TestNG plug-in in Eclipse from Market Place
3. Create a new Maven project (say : CucumberSeleniumTestNG)
4. Add cucumber-java, cucumber-testng and selenium dependencies in the pom.xml
5. Add Maven compiler dependency in pom.xml 
6. Create feature files(Gherkhin script) in src/main/resources folder
7. Create BasePage class for driver initialization and 
     create Hooks class for cucumber
     @BeforeAll and 
     @AfterAll
      that runs before all scenarios or after all the scenarios
      (Note that these are NOT TestNG annotations)
8. Write Step Definition Or Glue Code for the feature files
9. Create TestNG Cucumber Runner class, CucumberRunner.java
11. Create testng.xml for the project
12. Run Tests from TestNG Tests
13. Run Tests from testng.xml
14. Run Tests from Command line
15. Test results analysis from Cucumber report
16. Test results analysis from TestNG report

Project structure: 


1. Download and install Cucumber plug-in in Eclipse from Market Place
2. Download and install TestNG plug-in in Eclipse from Market Place
3. Create a new Maven project (say : CucumberSeleniumTestNG)
4. Add cucumber-java, cucumber-testng and selenium dependencies in the pom.xml
5. Add Maven compiler dependency in pom.xml 
pom.xml
Add the cucumber, testng and selenium dependencies and maven compiler as starting point. 
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>CucumberSeleniumTestNG</groupId>
<artifactId>CucumberSeleniumTestNG</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.4.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.3.0</version>
</dependency>

</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

6. Create feature files(Gherkhin script) in src/main/resources folder

HRMLogin.feature
Gherikn script for login validation 
@HRMLogin
Feature: Login to HRM Application
I want to use this template for HRM Login page

@LoginValidCredentials
Scenario: LoginValidCredentials
Given User is on login page
When User enters username as "Admin" and password as "admin123"
Then User should be able to login successfully

Dashboard.feature
There are two sceanrios in this feature file
@Dasbhoard
Feature: Dashboard page
I want to use this template for my Dashboard Page

@DashboardTabCountOfQuickLaunhElements
Scenario: DashboardTabCountOfQuickLaunhElements
Then User finds the list of quick launch elements

  @DirectoryTabNavigationFromDashbaordTab
Scenario: DirectoryTabNavigationFromDashboardTab Then User clicks on Directory tab and verifies the navigation

Directory.feature
There is a scenario with Background added to the feature
@Directory
Feature: Dashboard page
I want to use this template for my Directory Page

Background:
Then User is on Directory page

@DirectoryTabIsSearchButtonDisplayed
Scenario: DirectoryTabIsSearchButtonDisplayed
Then Is Search button displayed

7. Create BasePage class for driver initialization and 
     create Hooks class for cucumber
     @BeforeAll and 
     @AfterAll
      that runs before all scenarios or after all the scenarios
      (Note that these are NOT TestNG annotations)

BasePage.java
In the BasePage we initiate the driver; if we want to do command line execution of scenarios from a generated jar, main() method has to be included and this class best suites for it. 
package com.sadakar.common;
import org.openqa.selenium.WebDriver;
public class BasePage {

public static WebDriver driver;

}

Hooks.java
In the BeforeAll (This is a cucumber annotation/hook) hook we are logging into the application and use this driver session for all the scenarios so multiple log-in for each scenario is avoidable except for login validation. 

quit the driver after executing all the scenarios is done using AfterAll hook (This is a cucumber annotation/hook)
package com.sadakar.common;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

import io.cucumber.java.AfterAll;
import io.cucumber.java.BeforeAll;

public class Hooks extends BasePage {

@BeforeAll
public static void setupDriver() throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login");
driver.findElement(By.xpath("//*[@id=\"txtUsername\"]")).sendKeys("Admin");
driver.findElement(By.xpath("//*[@id=\"txtPassword\"]")).sendKeys("admin123");
driver.findElement(By.id("btnLogin")).submit();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
}

@AfterAll
public static void quitDriver() throws Exception {
driver.quit();
}

}

8. Write Step Definition Or Glue Code for the feature files
HRMLoginPage.java

We are already in logged in into the application in BeforeAll hook - so how to validate login ? 
When the driver begins executing this scenario, we quit the driver (driver.quit()) first and then a initiatate  a new driver and then logging back to the application that means the new driver is alive. 

As the cucumber scenarios executes randomly, if there are any other scenarios to be executed those scenarios will use the secondly generated driver from the login done page. 

package com.sadakar.stepdefinitions;

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

import com.sadakar.common.BasePage;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

public class HRMLoginPage extends BasePage {

@Given("User is on login page")
public static void homePage() throws InterruptedException {

driver.quit();

System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login");

}

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

driver.findElement(By.xpath("//*[@id=\"txtUsername\"]")).sendKeys(userName);
driver.findElement(By.xpath("//*[@id=\"txtPassword\"]")).sendKeys(password);
}

@Then("User should be able to login successfully")
public void clickSubmitLogin() {
driver.findElement(By.id("btnLogin")).submit();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
}

}

DashboardPage.java
There are two scenarios in Dashboard.feature file , one scenario is to count the elements and other scenario is to navigate from Dashboard to Dictionary. 
In this class, we have the step definition code for those two scenarios. 
package com.sadakar.stepdefinitions;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;

import com.sadakar.common.BasePage;

import io.cucumber.java.en.Then;

public class DashboardPage extends BasePage {

@Then("User finds the list of quick launch elements")
public void listOfQuickLaunchElementsOnDashboardPage() {

// Adding table data of a row to WebElement List
List<WebElement> actualListOfQuickLaunchElements = driver
.findElements(By.xpath("//*[@id=\"dashboard-quick-launch-panel-menu_holder\"]/table/tbody/tr/td"));

// Display the table data of row from the WebElementList
for (WebElement ele : actualListOfQuickLaunchElements) {
System.out.println(ele.getText());
}

// Display the size of WebElement List
System.out.println("Size of Quick launch elements : " + actualListOfQuickLaunchElements.size());

// Adding WebElements List to a ArrayList
List<String> quickLaunchElementsArrayList = new ArrayList<String>();
for (WebElement ele : actualListOfQuickLaunchElements) {
quickLaunchElementsArrayList.add(ele.getText());
}
// Displaying the WebElements from the ArrayList
for (WebElement s : actualListOfQuickLaunchElements) {
System.out.println(s.getText());
}
// Size of the ArrayList
System.out.println("Size of Array list : " + quickLaunchElementsArrayList.size());

// Preparing expected list of elements

@SuppressWarnings("serial")
List<String> expecteListOfQuickLaunchElements = new ArrayList<String>() {
{
add("Assign Leave");
add("Leave List");
add("Timesheets");
add("Apply Leave");
add("My Leave");
add("My Timesheet");
}
};

// comparing actual list with expected list
for (int i = 0; i < actualListOfQuickLaunchElements.size(); i++) {
String actualLabels = actualListOfQuickLaunchElements.get(i).getText();
String expectedLabels = expecteListOfQuickLaunchElements.get(i);
Assert.assertEquals(actualLabels, expectedLabels);
}
}

@Then("User clicks on Directory tab and verifies the navigation")
public void navigateToDirectoryTabFromDashbaordTab() {

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
driver.findElement(By.xpath("//*[@id=\"menu_directory_viewDirectory\"]")).click();
}
}

DirectoryPage.java
In the Directory feature we are validation whether the Search button is displayed or not. 
package com.sadakar.stepdefinitions;

import org.openqa.selenium.By;

import com.sadakar.common.BasePage;

import io.cucumber.java.en.Then;

public class DirectoryPage extends BasePage{

@Then("User is on Directory page")
public void user_is_on_directory_page() {
driver.findElement(By.xpath("//*[@id=\"menu_directory_viewDirectory\"]/b")).click();
}

@Then("Is Search button displayed")
public void isSearchButtonDisplayed() {

driver.findElement(By.xpath("//*[@id=\"searchBtn\"]")).isDisplayed();
}
}

9. Create TestNG Cucumber Runner class, CucumberRunner.java
CucumberRunner.java
In the cucumber 7 the tags takes new format 
For example: 
Single tag : 
tags="@LoginValidCredentials",

Two tags :
tags="@LoginValidCredentials or @DashboardTabCountOfQuickLaunhElements",

Negate a tag : 
tags="@LoginValidCredentials and not @DashboardTabCountOfQuickLaunhElements", 

CucumberRunner class extends the AbstractTestNGCucumberTests

package com.sadakar.testng.runner;

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(


//tags="@LoginValidCredentials",
//tags="@DashboardTabCountOfQuickLaunhElements",
//tags="@DirectoryTabNavigationFromDashboardTab",
//tags="@DirectoryTabIsSearchButtonDisplayed",
tags="@LoginValidCredentials or @DashboardTabCountOfQuickLaunhElements or @DirectoryTabNavigationFromDashboardTab or @DirectoryTabIsSearchButtonDisplayed",

//tags="@LoginValidCredentials and not @DashboardTabCountOfQuickLaunhElements and not @DirectoryTabNavigationFromDashboardTab or @DirectoryTabIsSearchButtonDisplayed",

features = "classpath:cucumberfeatures", glue = { "com.sadakar.common", "com.sadakar.stepdefinitions",
"com.sadakar.testng.runner", "com.inovalon.cucumber.common" },

plugin = { "pretty", "json:target/cucumber-reports/cucumber.json", "html:target/cucumber-reports/cucumberreport.html" },

monochrome = true)
public class CucumberRunner extends AbstractTestNGCucumberTests {


}

11. Create testng.xml for the project
testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="com.sadakar.testng.runner.CucumberRunner"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

12. Run Tests from TestNG Tests



13. Run Tests from testng.xml
14. Run Tests from Command line
    <TBD>
15. Test results analysis from Cucumber report


16. Test results analysis from TestNG report

Click on the images to Zoom In




Emailable-report.html:

index.html


I hope you find it useful ! Stay tuned for more learnings. 

July 1, 2022

June 29, 2022

Hi,  

Tap on the images to view in gallery. 

Java installation, JAVA_HOME, Path

1.  Download java from Oracle and install as executable. 
2. JAVA_HOME: 


3. Path:




Maven installation, MAVEN_HOME, Path

1.  Download maven zip file from Maven Download and extract the zip file 
2. Keep the folder in Program Files at : C:\Program Files\apache-maven-3.8.6-bin
3. MAVEN_HOME

4. Maven Path


June 29, 2022

June 21, 2022

Hi

Problem Statement: 

Compare the below table row data elements(expected results) with actual elements(actual results) in selenium ? 

Solution: 
1) Find the td elements of the tr using findElements method and add them to List<WebElement>. This would become the actual elements from the web page. 
2) Take a ListArray for the expected results and add the elements using add method
3) Now compare the elements by converting both web elements and array elements. 

In the code snippet below, additionally converted the WebElement to ArrayList and the size of these are displayed using size() method. 

Github:  https://github.com/sadakar/CucumberSeleniumTestNG.git
Project is based on : Cucumber , TestNG frameworks. 




Cucumber Gherkin script:
@tag
Feature: Login to HRM Application
I want to use this template for my feature file

Background:
Given User is on home page
When User enters username as "Admin"
And User enters password as "admin123"

@List
Scenario: Login with valid credentials
Then User finds the list of quick launch elements

Step definitions:
package com.sadakar.stepdefinitions;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.sadakar.common.BasePage;

import io.cucumber.java.en.Then;

public class QuickLaunchWebElementsList extends BasePage {

@Then("User finds the list of quick launch elements")
public void User_finds_the_list_of_quick_launch_elements() {

// Adding table data of a row to WebElement List
List<WebElement> actualListOfQuickLaunchElements = driver
.findElements(By.xpath("//*[@id=\"dashboard-quick-launch-panel-menu_holder\"]/table/tbody/tr/td"));


// Display the table data of row from the WebElementList
for (WebElement ele : actualListOfQuickLaunchElements) {
System.out.println(ele.getText());
}

// Display the size of WebElement List
System.out.println("Size of Quick launch elements : " + actualListOfQuickLaunchElements.size());

// Adding WebElements List to a ArrayList
List<String> quickLaunchElementsArrayList = new ArrayList<String>();
for (WebElement ele : actualListOfQuickLaunchElements) {
quickLaunchElementsArrayList.add(ele.getText());
}
// Displaying the WebElements from the ArrayList
for (WebElement s : actualListOfQuickLaunchElements) {
System.out.println(s.getText());
}
// Size of the ArrayList
System.out.println("Size of Array list : " + quickLaunchElementsArrayList.size());


//Preparing expected list of elements
@SuppressWarnings("serial")
List<String> expecteListOfQuickLaunchElements= new ArrayList<String>() {
{
add("Assign Leave");
add("Leave List");
add("Timesheets");
add("Apply Leave");
add("My Leave");
add("My Timesheet");
}
};

// comparing actual list with expected list
for(int i=0;i<actualListOfQuickLaunchElements.size();i++) {
String actualLabels = actualListOfQuickLaunchElements.get(i).getText();
String expectedLabels = expecteListOfQuickLaunchElements.get(i);
Assert.assertEquals(actualLabels, expectedLabels);
}

}
}

I hope this helps some in the community!

June 21, 2022

May 23, 2022

1. Create a Maven Project 
2. Add Selenium, TestNG, Cucumber dependencies in pom.xml 
3. Add maven compiler plugin in pom.xml
4. Create feature file 
5. Create BasePage class 
6. Create Hooks
7. Create CucumberRunner class 
8. Create Step Definition class 
9. Run the project with TestNG framework. 

10. Run the tests using TestNG.xml 
11. Reporting : Cucumber Reporting
12. Reporting : TestNG Reporting. 


Download the project : Click Me

 1. Create a Maven Project 

While Creating the Maven Project the Structure would be as shown in below image



After Creating All the Source Code




2. Add Selenium, TestNG, Cucumber dependencies in pom.xml 
3. Add maven compiler plugin in pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>CucumberSeleniumTestNG</groupId>
<artifactId>CucumberSeleniumTestNG</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.3.2</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->


</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.9.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

4. Create feature file.
@tag
Feature: Login to HRM Application
I want to use this template for my feature file

@ValidCredentials
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 successfully

5. Create BasePage class
package com.sadakar.common;
import org.openqa.selenium.WebDriver;
public class BasePage {

public static WebDriver driver;

}

6. Create Hooks
package com.sadakar.common;

import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.After;
import io.cucumber.java.Before;

public class Hooks extends BasePage {

@Before
public void setupDriver() throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");

driver = new ChromeDriver();
driver.manage().window().maximize();
Thread.sleep(2000);
}

@After
public void quit() throws Exception {

driver.quit();
}

}

7. Create CucumberRunner class
package com.sadakar.testng.runner;

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(tags = " @ValidCredentials",

features = "classpath:cucumberfeatures", glue = { "com.sadakar.common", "com.sadakar.stepdefinitions",
"com.sadakar.testng.runner", "com.inovalon.cucumber.common" },

plugin = { "pretty", "json:target/cucumber-reports/cucumber.json", "html:target/cucumber-reports/cucumberreport.html" }, monochrome = true)
public class CucumberRunner extends AbstractTestNGCucumberTests {

}
8. Create Step Definition class
package com.sadakar.stepdefinitions;

import org.openqa.selenium.By;

import com.sadakar.common.BasePage;

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

public class HRMLoginPage extends BasePage {


@Given("User is on home page")
public void user_is_on_home_page() {
driver.get("https://opensource-demo.orangehrmlive.com/");
}

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

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

@When("User enters password as {string}")
public void user_enters_password_as(String password) {
System.out.println("Password entered");
driver.findElement(By.name("txtPassword")).sendKeys(password);

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

@Then("User should be able to login successfully")
public void user_should_be_able_to_login_successfully() {
String newPageText = driver.findElement(By.id("welcome")).getText();
System.out.println("newPageText =" + newPageText);
}
}

9. Run the project with TestNG framework.


10. Run the tests using TestNG.xml
<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite1">
<test name = "HRMTests">
<classes>
<class name = "com.sadakar.testng.runner.CucumberRunner"/>
</classes>
</test>
</suite>

11. Reporting : Cucumber Reporting
plugin = { "pretty", "json:target/cucumber-reports/cucumber.json",	"html:target/cucumber-reports/cucumberreport.html" }



12. Reporting : TestNG Reporting




May 23, 2022

May 19, 2022

 Hi, 

Bearer token response body: 

{
"token_field1": "TokenField1ValueInEncodedFormat",
"token_lasts_for_howmanyms": 7200, //2 mins
"type_of_token": "Bearer"
}

Write below script in "Tests" tab of SOAP POST request (not in Pre-request scripts)

NOTE:
Token generated will get stored in VarJWTToken where VarJWTToken is an environment variable created in the environment.  
var data = JSON.parse(responseBody);
postman.clearEnvironmentVariable(
"VarJWTToken");
postman.setEnvironmentVariable(
"VarJWTToken", data.token_field1);

Use the VarJWTToken environment variable in request Authorization as shown in below image: 
Postman collection format: 
Token  (Token generated in this request will get stored in environment variable)
   SOAP POST Request (using environment variable POST authentication will be done) 

May 19, 2022

Basic REST XML template using REST Assured 

package com.sadakar.api.common;

import static org.testng.Assert.assertNotEqualsDeep;

import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;

public class RESTXMLPost {


@Test
public void post() {
String requestBody =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+"<tag1 subtag1=\"value1\" >\r\n"
+"<tag2>\r\n"
+"<tag2Subtag>value</tag2Subtag>\r\n"
+"</tag1>";


given()
.log().all()
.baseUri("https://testurl/api/endPoint")
.contentType("application/xml")
.accept("application/xml")
.header("headerName", "headerValue")
.body(requestBody)
.when()
.post()
.then()
.log().all()
.assertThat()
.statusCode(200)
.and()
.contentType("application/xml");
}
}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>APIAutomation</groupId>
<artifactId>APIAutomation</artifactId>
<version>0.0.1-SNAPSHOT</version>

<dependencies>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.0.1</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.5</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>

</dependencies>

</project>



May 19, 2022

Hi, 

1) Print the selected environment on console
2) if else condition to execute a particular test based on the environment. 
 
console.info(pm.environment.name);
pm.environment.set("currentEnvName",pm.environment.name);
var environementName = pm.environment.get("currentEnvName");
console.log("Environement Name Current Used Is : "+environementName);

if(pm.environment.name=="Server1" || pm.environment.name=="Server2"
||pm.environment.name=="Server3"||pm.environment.name=="Server4" ){
postman.setNextRequest(null);
} else
{
postman.setNextRequest("TestCase123");
}

References:
https://stackoverflow.com/questions/58612238/postman-get-the-environment-name-as-a-variable

May 19, 2022

Pages

Feedback