Filter by tags:
July 15, 2022
If else tests - based on xml response has certain text/string in postman | pm.response.text().has
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
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 | if( pm.response.text().has("Text1")){ |
July 15, 2022
Append date and time to newman html extra report
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
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
D:/postman/newman/TestCollectionReport_20221507_1720.html
July 15, 2022
July 6, 2022
Integration of Cucumber with Selenium and TestNG, Maven | end to end example using 7.1 dependencie…
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
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
Test Cases/Scenarios:
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!
i.e., the usage of src/test/java and src/test/resources
- 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
<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
@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: 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
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.
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.
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.
Cucumber & TestNG runner class, RunCucumberTest.java
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
<?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>
[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
Step 11: Run Tests from command line
July 6, 2022
July 1, 2022
Integration of Cucumber with TestNG and Selenium | Validate Login page with one session and Validat…
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
Integration of Cucumber with Selenium and TestNG, Maven | end to end example using 7.1 dependencies
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.
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.
Steps to create the frame work:
2. Download and install TestNG plug-in in Eclipse from Market Place
3. Create a new Maven project (say : CucumberSeleniumTestNG)
6. Create feature files(Gherkhin script) in src/main/resources folder
@BeforeAll and
that runs before all scenarios or after all the scenarios
(Note that these are NOT TestNG annotations)
16. Test results analysis from TestNG report
2. Download and install TestNG plug-in in Eclipse from Market Place
3. Create a new Maven project (say : CucumberSeleniumTestNG)
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>
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
@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
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
@BeforeAll and
that runs before all scenarios or after all the scenarios
(Note that these are NOT TestNG annotations)
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;
}
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.
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();
}
}
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.
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));
}
}
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();
}
}
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();
}
}
tags="@LoginValidCredentials",
tags="@LoginValidCredentials or @DashboardTabCountOfQuickLaunhElements",
tags="@LoginValidCredentials and not @DashboardTabCountOfQuickLaunhElements",
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 {
}
<?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 -->
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 file2. Keep the folder in Program Files at : C:\Program Files\apache-maven-3.8.6-bin
3. MAVEN_HOME

June 29, 2022
June 21, 2022
Selenium | Adding table data elements to List using findElements | Adding WebElement elements to Ar…
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
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
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);
}
}
}
June 21, 2022
May 23, 2022
Integration of Cucumber with Selenium and TestNG | Orange HRM Login Example (1 feature file, 1 sce…
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
<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>
@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
package com.sadakar.common;
import org.openqa.selenium.WebDriver;
public class BasePage {
public static WebDriver driver;
}
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();
}
}
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 {
}
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);
}
}
<?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>
plugin = { "pretty", "json:target/cucumber-reports/cucumber.json", "html:target/cucumber-reports/cucumberreport.html" }
May 23, 2022
May 19, 2022
How to set JWT Token as postman environment variable and use it for "Bearer Token" type i…
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
Hi,
Bearer token response body:
{
"token_field1": "TokenField1ValueInEncodedFormat",
"token_lasts_for_howmanyms": 7200, //2 mins
"type_of_token": "Bearer"
}
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);
May 19, 2022
Basic REST XML POST request template using REST Assured and testng
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
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");
}
}
<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
Print the environment name on console and based on environment selection write if else condition to…
( JasperSoft BI Suite Tutorials - Sadakar Pochampalli )
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");
}
May 19, 2022
Pages
About
Planet Jaspersoft aggregates blog posts from our community. If you would like your blog to be included in the Planet, please follow this help guide. Or just click this link to go straight to your Planet Feeds.
Feed Sources
- JasperSoft BI Suite Tutorials - Sadakar Pochampalli (273) Apply JasperSoft BI Suite Tutorials - Sadakar Pochampalli filter
- Technology Blog (50) Apply Technology Blog filter
- Jaspersoft Tech Talks (41) Apply Jaspersoft Tech Talks filter
- Jaspersoft Tutorials (30) Apply Jaspersoft Tutorials filter
- The Open Book on BI (26) Apply The Open Book on BI filter
- Rajesh Sirsikar (22) Apply Rajesh Sirsikar filter
- Bekwam Data as a Service (21) Apply Bekwam Data as a Service filter
- AgileTech - Ankur Gupta (19) Apply AgileTech - Ankur Gupta filter
- Ankur Gupta - Youtube (17) Apply Ankur Gupta - Youtube filter
- Digital Gene (15) Apply Digital Gene filter
- Tech Poet (13) Apply Tech Poet filter
- iTransparent - Jaspersoft Blog (9) Apply iTransparent - Jaspersoft Blog filter
- Paco Saucedo's blog » JasperReports (6) Apply Paco Saucedo's blog » JasperReports filter
- David Hoppmann's JasperServer Posts (2) Apply David Hoppmann's JasperServer Posts filter
- Jasper Related Posts from Wedjaa (1) Apply Jasper Related Posts from Wedjaa filter