@@TestNG 3
@@TestNG 3
Test NG Program
What is Test-NG
Test-NG is an automation testing framework in which NG stands for “Next Generation”. Test-NG is inspired by JUnit
which uses the annotations (@).
WebDriver has no native mechanism for generating reports. TestNG can generate the report in a proper &
readable format.
The same test cases can be executed multiple times without loops.
Using testNG, you can execute multiple test cases on multiple browsers.
The TestNG framework can be easily integrated with tools like TestNG Maven, Jenkins, etc.
3. We used the @Test annotation. @Test is used to tell that the method under it is a test case.
package TestNG;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class TestNG_Demo {
@Test
//We need to write method
1
public void verifyPageTitle() {
//Assert
Assert.assertEquals(actualTitle, expectedTitle);
Test NG Example
package TestNG;
import org.testng.annotations.Test;
@Test
public void test1() {
System.out.println("Test Case 1");
}
@Test
public void test2() {
System.out.println("Test Case 2");
}
}
In Test-NG Frame Work, we must create a Testng.xml file to run and handle multiple test classes. TestNG.xml file
is an XML file that contains all the test configurations and this XML file can be used to run and organize our test.
In the testng.xml file, we configure our test run, set test dependency, include or exclude any test, method, class or
package and set priority etc.
2
Testng.xml file is also is used for TestNG Parameters. TestNG Parameters are the arguments that we pass to the
test methods.
Step 1: After writing code you need to convert into Test NG
3
You can see in Project Explore inside package testng.xml file generated.
4
Now I want to run the xml file for that you need to right click on testng.xml filr and run as ⇒ TestNG Sunit
5
Enable/ Disable Test Cases and Regular Expressions
<methods>
<exclude name = "MethodName"></exclude> /*if you want to disable
the perticular method at that time you can used exclude tag*/
<include name = "MethodName"></include> /*execute the perticular
method then you can used include tag*/
</methods>
By Regular Expressions :
package TestNG;
import org.testng.annotations.Test;
@Test(enabled = false)
public void MobileLoginPersonalLoan() {
System.out.println("Mobile Login Personal Loan");
}
@Test(enabled = false)
public void WebLoginPersonalLoan() {
System.out.println("Web Login Personal Loan");
}
@Test(enabled = false)
public void APILoginPersonalLoan() {
System.out.println("API Login Personal Loan");
}
@Test
public void MobileLoginAutomobileLoan() {
System.out.println("Mobile Login Automobile Loan");
}
@Test
public void WebLoginAutomobileLoan() {
System.out.println("Web Login Automobile Loan");
}
6
@Test
public void APILoginAutomationLoan() {
System.out.println("API Login Automation Loan");
}
}
By XML
Annotations
TestNG identifies the methods it is interested in, by looking up annotations. Hence, method names are not
restricted to any pattern or format.
Annotations are strongly typed, so the compiler will flag any mistakes right away.
@Test(description = “ ”)
package AnnotationAttributes;
import org.testng.annotations.Test;
7
public class Description {
@Test(timeOut = 200)
package AnnotationAttributes;
import org.testng.annotations.Test;
@Test(timeOut = 200)
public void test2() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Test Case 2");
}
package AnnotationAttributes;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
driver.get("https://ultimateqa.com/dummy-automation-websites/");
driver.close();
}
}
package AnnotationAttributes;
import org.testng.annotations.Test;
@Test(dependsOnMethods = {"test2"})
8
public void test1() {
System.out.println("Test Passed 1");
}
@Test
public void test2() {
System.out.println("Test Passed 2");
}
package AnnotationAttributes;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
@Test(dependsOnMethods = {"LaunchBrowser"})
public void LoginPage() {
WebDriver driver = new ChromeDriver();
driver.get("https://ultimateqa.com/dummy-automation-websites/");
driver.close();
}
@Test
public void LaunchBrowser() {
WebDriverManager.chromedriver().setup();
}
}
@Test(priority=2)
package AnnotationAttributes;
import org.testng.annotations.Test;
@Test(priority=1)
public void c() {
System.out.println("C passed");
}
@Test(enabled = false)
package AnnotationAttributes;
import org.testng.annotations.Test;
@Test(groups = "automobile")
public void aman() {
System.out.println("Yes I am Aman ");
}
@Test(groups = "automobile")
public void akshay() {
System.out.println("Yes I am Akshay");
}
@Test(groups = "IT")
9
public void ram() {
System.out.println("Yes I am Ram");
}
@Test(groups = "IT")
public void ashish() {
System.out.println("Yes I am Ashish");
}
}
Test-NG Parameters
Test-NG Parameters are the arguments that we pass to the test methods. There are two ways through which we
can pass the parameters to the test methods.
@Parameters({”param1”,”param2”,”param3”})
Ex1
package TestNG;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
@Test
@Parameters({"a","b"})
public void add(int a, int b) {
System.out.println(a+b);
}
@Test
@Parameters({"a","b"})
public void sub(int a ,int b) {
System.out.println(a-b);
}
Ex2
Real Time
package TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
10
@Test
public void search(String sdata) {
WebDriverManager.edgedriver().setup();
WebDriver driver = new EdgeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.quit();
}
}
package TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.quit();
}
}
Data Providers
Similar to Test Ng Parameters, Data Providers are a means to pass data to test methods in Test NG. Using Data
Provider in Test NG, we can easily inject multiple values into the the same test case. It comes inbuilt in Test Ng and
is popularly used in data - driven frameworks.
Syntax:
11
public Object[][] dataProviderfunc(){
return new Object[][]{values}
}
1. The Data Provider annotation has a single attribute called name, which you can select as per your convenience.
2. Data Providers are separate methods used in test functions, which means that this annotation is not used on
test functions like the test NG parameters.
4. In case you do not define a name for the Data Provider, The Data Provider method name is considered its
default name. So the name of the Data Provider calls the Data Provider method.
Test Scenario :
package TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
@DataProvider(name="SearchDataSet")
public Object[][] searchData(){
Object[][] searchKeyWord = new Object[3][2];
searchKeyWord[0][0] = "India";
searchKeyWord[0][1] = "Qutub Minar";
searchKeyWord[1][0] = "Agra";
searchKeyWord[1][1] = "Taj Mahal";
searchKeyWord[2][0] = "Hyderabad";
searchKeyWord[2][1] = "Charminar";
return searchKeyWord;
@Test(dataProvider = "SearchDataSet")
public void TestCaseGoogleSearch(String country, String monument) {
WebDriverManager.edgedriver().setup();
WebDriver driver = new EdgeDriver();
driver.manage().window().maximize();
//driver.navigate().to("https://www.google.com/");
driver.get("https://www.google.com/");
3 Hyderabad Charminar
Parallel Testing
12
In parallel test case what we do?
Method 1(); - 1 m
Method 2(); - 1 m
Method 3(); - 1 m
We Can Execute
All the test cases inside a Java class will run parallel methods
All the test cases inside <test> tag for testing xml file will run parallel.
package TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
//Maximize
driver.manage().window().maximize();
driver.get("https://www.saucedemo.com/");
Assert.assertEquals(actualTitle, expectedTitle);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.quit();
}
@Test
public void verifyLogo() {
WebDriverManager.edgedriver().setup();
WebDriver driver = new EdgeDriver();
driver.manage().window().maximize();
driver.get("https://www.saucedemo.com/");
}
}
13
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "https://test.org/testng-1.0.dtd">
<suite name = "Suite" parallel = "methods" thread-count = "2">
<test name = "Test">
<classes>
<class name = "TestNG.TestNG.ParallelTestDemo1">
</classes>
</test><!-- Test -->
</suite><!-- Suite -->
package TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
@Test
public void verifyLoginFunctionality() {
WebDriverManager.edgedriver().setup();
// //ChromeOptions
// ChromeOptions options = new ChromeOptions();
// options.addArguments("--incognito");
//Launch browser
WebDriver driver = new EdgeDriver();
driver.manage().window().maximize();
driver.get("https://www.saucedemo.com/");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.quit();
}
Listeners
14
Based on result on test cases what post action we need for that purpose we used Listeners. Listener is a
Interface
1. IAnnotationTransformer.
2. IAnnotationTransformer2.
3. IConfigurable.
4. IConfigurationListener.
5. IExecutionListener.
6. IHookable.
7. IInvokedMethodListener.
8. IInvokedMethodListener2.
9. IMethodInterceptor.
10. IReporter.
11. ISuiteListener
12. ITestListener
1. onTestStart(): An on TestStart() is invoked only when any test method gets started.
4. onTestSkipped(): An on TestSkipped() run only when any test method has been skipped.
6. onFinish(): An onFinish() is invoked when any test case finishes its execution.
7. onTestFailedButWithinSuccessPercentage(): This method is invoked each time when the test method
fails but within success percentage.
@Test
public void testFail(){
System.out.println("Test Case Fail");
Asserts.assetTrue("false");
}
@Test
15
public void testPass(){
System.out.println("Test Case Pass");
Asserts.assertTrue("True");
}
@Test
public void testSkipped(){
System.out.println("skipp test case");
throw now SkippException("Skip on Exception................... ");
}
}
Listener Class
}
}
XML File
Listener Program2
package TestNG.TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
16
@Listeners(TestNG.TestNG.ListenerClass.class)
public class ListenerDemo {
@Test
public void login() {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
WebDriver driver = new ChromeDriver(options);
//Maximize window
driver.manage().window().maximize();
//Launch URL
driver.get("https://www.saucedemo.com/");
@Test
public void testfail() {
//if my test case failed at that time this execute
System.out.println("Failed test case");
Assert.assertTrue(false);
}
@Test
public void testSkipped() {
//Skip exception
System.out.println("skipped test case");
throw new SkipException("skip exception thrown...");
}
}
Listener Class
package TestNG.TestNG;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
17
XML File
file:///E:/New%20Eclips%20For%20Cucumber/My%20Eclipse%20program/DecemberBatch_TestNG_FrameWor
output/emailable-report.html#summary
Index.html Report
file:///E:/New%20Eclips%20For%20Cucumber/My%20Eclipse%20program/DecemberBatch_TestNG_FrameWor
output/index.html#login
Batch Testing
A test suite is a collection of test cases. Test suites helps in grouping test case.
You can categorize test suites based on functionality, module, environment, or something else.
Test Scenario
VerifyTitle()
VerifyLogo()
LoginByEmail()
AddProductToCart()
SelectQuantity()
PaymentTest CashOnDelivery()
NetBanking()
Batch Testing
HomeScreenTest
package BatchTesting;
import org.testng.annotations.Test;
@Test
public void LaunchApplication() {
System.out.println("Application launch passed");
}
@Test
public void VerfiyTitle() {
System.out.println("Verify title passed");
18
}
@Test
public void VerifyLogo() {
System.out.println("Verify Logo passed");
}
}
LoginTest
package BatchTesting;
import org.testng.annotations.Test;
@Test
public void LoginByMobileNumber() {
System.out.println("Login by mobile passed ");
}
@Test
public void LoginByEmail() {
System.out.println("Login by email passed");
}
}
ProductPageTest
package BatchTesting;
import org.testng.annotations.Test;
@Test
public void AddProductToWishList() {
System.out.println("Add product to wish list passed");
}
@Test
public void AddProductToCart() {
System.out.println("AddProductToCart passed");
}
@Test
public void SelectQuantity() {
System.out.println("SelectQuantity is passed");
}
}
PaymentTest
package BatchTesting;
import org.testng.annotations.Test;
@Test
public void CashOnDelivery() {
System.out.println("CashOnDelivery is passed");
}
@Test
public void NetBanking() {
System.out.println("NetBanking is passed");
}
}
19
<?xml version="1.0" encoding="UTF-8"?>
<suite name="SanityTestSuite">
<test name="Sanity Testing">
<classes>
<class name="BatchTesting.HomeScreenTest" />
<class name="BatchTesting.LoginTest" />
</classes>
</test>
</suite>
Functional Testing
Master Suite
What is Assertions
Assertions in Test NG are used for validating the test methods and to verify that the expected result and the
actual result matched or not.
Types of Assertions
Hard Assertion
Hard Assertion is an Assertion that immediately throws the AssertException when the test case is failed. A
Hard Assertion contains the following methods
Hard Assertion verify the actual and expected result is not match at that time they show error
AssertException error.
3 AssertTrue Assert.assertTrue(condition)
4 AssertFalse Assert.assertFalse(condition)
Soft Assertion
Soft Assert does not throw an exception immediately when the assertion fails, collects them and carries out
with the next validation. This accumulates the errors in each @Test execution. To use testng soft assertion,
you have to use testng SoftAssert class
Test Scenario
2. Open URL
20
3. Verify Title of the webpage
package TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
@Test
public void testMethod() {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
WebDriver driver = new ChromeDriver(options);
//open url
driver.get("https://testautomationpractice.blogspot.com/");
driver.close();
}
}
package TestNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import io.github.bonigarcia.wdm.WebDriverManager;
@Test
public void testMethod() {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
WebDriver driver = new ChromeDriver(options);
21
String expectedTitle = "Automation Testing Practice1";
String actualTitle = driver.getTitle();
softVerify.assertEquals(expectedTitle, actualTitle,"Title is verify");
driver.close();
}
}
Invocation Count
In Test NG, InvocationCount attribute is used to run single test case multiple time.
Where num = number of times you want to run this test method
Syntax
@Test(invocationCount = num)
InvocationCount
package TestNG;
import org.testng.annotations.Test;
@Test(invocationCount = 5)
public void testMethod1() {
System.out.println("Test method1...");
}
XML
package TestNG;
import org.testng.ITestContext;
import org.testng.annotations.Test;
@Test(invocationCount = 5)
22
public void testMethod1(ITestContext context) {
int currentInvocation = context.getAllTestMethods()[0].getCurrentInvocationCount();
System.out.println("Executing: " + currentInvocation);
System.out.println("Test method1...");
}
@Test(invocationCount = 3)
public void testMethod2(ITestContext context) {
int currentInvocation = context.getAllTestMethods()[1].getCurrentInvocationCount();
System.out.println("Executing: " + currentInvocation);
System.out.println("Test method2...");
}
}
Logging
What is Logging
Logging means some way to indicate the state of the system at runtime. The log messages have to provide the
required information to understand what the application does internally during runtime.
What is Log4j
Log4j logging framework which is written in Java. It is an open-source logging API for java.
Download Dependency's
//https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core/2.20.0
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.20.0</version>
</dependency>
//https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api/2.20.0
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.20.0</version>
</dependency>
//
Log4j2.xml
<Loggers>
<Root level = "all"/>
<AppenderRef ref = "STDOUT"/>
23
</Loggers>
</Configuration>
This is also a configuration file having all runtime configurations used by log4j.
import org.apache.logging.log4j.*;
https://logging.apache.org/log4j/2.x/manual/customloglevels.html
package Demo;
import org.apache.logging.log4j.*;
}
}
Log4j2.properties file
src/main/resource
1. New
2. Others
3. General
4. File
5. log4j2.properties
log4j2.properties
//name = PropertiesConfig
property.filename = logs
appenders = console, file
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.file.type = File
appender.file.name = LOGFILE
appender.file.filename= ${filename}/mylog.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
loggers=file
logger.file.name=LoggerDemo
logger.file.level = debug
24
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE
rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
Page Object Model (POM) is a design pattern, popularly used in test automation that creates Object Repository
for web UI elements
Under POM
There is separate class for each web page to identify web elements of that web page and methods which
perform operations on those Web Elements
@FindBy(id="password")
WebElement password;
@FindBy(id="login-button")
WebElement loginBtn;
25
public void enterPassword(String pwd){
driver.findElement(password).sendKeys(pwd);
}
public void clickOnLoginBtn(){
driver.findElement(loginBtn).click();
}
//open url
driver.get("https://www.saucedemo.com/");
LoginPage(WebDriver d){
driver = d;
}
By username = By.id("user-name");
By password = By.id("password");
By loginBtn = By.id("login-button");
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
26
//Crate object of LoginPage
LoginPage LoginPg = new LoginPage(driver);
//open url
driver.get("https://www.saucedemo.com/");
LohinPg.enterUsername("standard_user");
LoginPg.enterPassword("secret_sauce");
LoginPg.clickOnLoginBtn();
Cross Browser
Cross-browser testing gives the confidence that the website behaviour is consistent across various
browsers.
Test Scenario
Simple one
@BeforeMethod
public void LaunchBrowser(){
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
@Test
public void verifyTitle(){
//open URL
driver.get("https://wwww.google.com");
String expectedTitle = "Google";
String actualTitle = driver.getTitle();
Assert.assertEquals(expectedTitle,actualTitle);
}
@AfterMethod
public void quiteBrowser(){
driver.quit();
}
}
XML
For Multiple
@BeforeMethod
@Parameters("browser")
public void LaunchBrowser(String browser){
27
switch(browser.toLowerCase()){
case "msedge":
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
break;
default:
driver = null;
break;
case "chrome":
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
break;
}
}
@Test
public void verifyTitle(){
//open URL
driver.get("https://wwww.google.com");
String expectedTitle = "Google";
String actualTitle = driver.getTitle();
Assert.assertEquals(expectedTitle,actualTitle);
}
@AfterMethod
public void quiteBrowser(){
driver.quit();
}
}
<test name="TestOnChrome">
<parameter name = "browser" value = "chrome"></parameter>
<classes>
<class name = "PackageName.ClassName">
</classes>
</test>
</suite>
But if the script is failing due to XPath and some valid reason then you have to maintain for re work on your
scripts.
Using testing-failed.xml
RetryLogicDemo
package RetryLogicDemo;
28
@Test
public void TestCasse01(){
@Test
public void TestCasse02(){
@Test
public void TestCasse03(){
Using the IRetryAnalyzer interface that is part of TestNG We need to override the retry method.
RetryLogicDemo
if(!result.isSuccess()){
if(counterForRetryAttepts<setMaxLimitforRetry){
counterForRetryAttempts++;
return true;
}
}
return false;
}
}
package RetryLogicDemo;
@Test(retryAnalyzer = RetryAnalyser.class)
public void TestCasse01(){
@Test(retryAnalyzer = RetryAnalyser.class)
public void TestCasse02(){
@Test(retryAnalyzer = RetryAnalyser.class)
public void TestCasse03(){
XML
29
</test>
</suite>
IAnnotationTransformer
RetryListener
import org.testng.IAnnotationTransformer;
testAnnotation.setRetryAnalyzer(RetryAnalyser.class);
}
}
XML
RetryLoginDemo
package RetryLogicDemo;
@Test
public void TestCasse01(){
@Test
public void TestCasse02(){
@Test(retryAnalyzer = RetryAnalyser.class)
public void TestCasse03(){
A HTTP cookie is comprised of information about the user and their preferences. It is a small piece of data sent from
Web Application and stored in Web Browser, while the user is browsing that website.
Program on Cookies
30
Cookies Example
package CookiesDemo;
//Enahance loop
for(Cookie ck : cookiesList){
System.out.println(ck.getName() + " " + ck.getValue());
}
//Create Cookie
Cookie cookieObje = new Cookie("TestCookie", "www.amazon.in");
/*********************************************************************/
//delete cookie
driver.manage().deleteCookie(cookieObje);
Encryption is the process of converting plain text data into an unreadable format in order to protect against
unauthorized access.
To secure our passwords/ sensitive data we can use the Base64 encoding scheme in Selenium WebDriver.
We will import this Base64 class in our script to decode password / Sensitive data.
package EncodePassword;
import org.apache.commons.codec.binary.Base64;
import org.openqa.selenium.By;
31
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import io.github.bonigarcia.wdm.WebDriverManager;
// //encode password
// String password = "secret_sauce";
//
// byte[] encodePassword = Base64.encodeBase64(password.getBytes());
//
// System.out.println(new String(encodePassword));
//c2VjcmV0X3NhdWNl
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
driver.manage().window().maximize();
driver.get("https://www.saucedemo.com/");
driver.findElement(By.id("user-name")).sendKeys("standard_user");
//decode password
byte[] decodedPassword = Base64.decodeBase64("c2VjcmV0X3NhdWNl");
driver.findElement(By.id("password")).sendKeys(new String(decodedPassword));
driver.findElement(By.id("login-button")).click();
driver.quit();
package Action;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import io.github.bonigarcia.wdm.WebDriverManager;
driver.manage().window().maximize();
driver.get("https://www.saucedemo.com/");
// driver.findElement(By.id("user-name")).sendKeys("standard_user");
// driver.findElement(By.id("password")).sendKeys("secret_sauce");
//
// driver.findElement(By.id("login-button")).click();
32
}
Data-driven testing is a test automation framework which stores test data in a table or spread spreadsheet format
(Eg. Excel File)
Using Java Classes and Apache POI library we can manipulate (read / write) Excel Files (Both XLS and XLSX file
format) in Selenium WebDriver.
Some points
poi-ooxml
Paste above dependencies in pom.xml of your maven project and save it.
package DataDriven;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
try {
inputStream = new FileInputStream(excelfile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ExcelWBook = new XSSFWorkbook(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
33
System.out.print(ExcelWSheet.getRow(currentRow).getCell(currentCell).toString());
System.out.print("\t");
}
System.out.println("\n");
}
ExcelWBook.close();
2. These can be used in a case where there is no need to view anything and our purpose is just to ensure that
all tests are getting executed successfully line by line.
3. When there is a need for executing parallel tests, UI-based browsers consume a lot of memory and/or
resources. Hence, here Headless browser is the preferred use.
4. When compared to Real Browsers, Headless Browsers are faster. So, these are chosen for faster execution.
1. As headless browsers are very fast, due to their faster page loading ability, sometimes it is difficult to debug
the issues.
2. When tests are to be performed in front of a user, where the user can interact with the team, referring to the
GUI and discussing where ever changes or corrections are required. In such a case, Headless Browsers
cannot be used and Real browser testing is done as it has GUI
3. As Headless Browsers don’t represent GUI, it is troublesome to report errors with the help of screenshots.
package HeadlessBrowsers;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import io.github.bonigarcia.wdm.WebDriverManager;
driver.get("https://www.saucedemo.com/");
System.out.println("Before login : " + driver.getTitle());
//Enter user-name
driver.findElement(By.id("user-name")).sendKeys("standard_user");
//Enter password
driver.findElement(By.id("password")).sendKeys("secret_sauce");
34
For Firefox Browser
For HTML
Html Unit Driver is a headless driver providing non-GUI implementation of Selenium WebDriver. It is written
in Java. This is inbuilt headless browser od Selenium WebDriver.
Download
htmlunit-driver-3.60.0-jar-with-dependencies.jar
From
https://github.com/SeleniumHQ/htmlunit-driver/releases
Test NG Reports
TestNG Reports are the default HTML reports which are generated once the test cases are executed using TestNG
index.html
emailable-report.html
Note: The Selenium web driver is used for automating the web application, but it wouldn’t generate any reports.
Example 1
package TestNG_Report_Demo;
import org.testng.annotations.Test;
@Test
public void testMethod1() {
System.out.println("Test Method 1 ...");
}
@Test
public void testMethod2() {
System.out.println("Test Method 2 ...");
}
@Test
public void testMethod3() {
System.out.println("Test Method 3 ...");
}
@Test
public void testMethod4() {
System.out.println("Test Method 4 ...");
}
}
with XML
Example 2 with scenario Open Google and search for India gate
35
package TestNG_Report_Demo;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
@Test
public void googleSearch() {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("http://www.google.com");
driver.close();
}
}
Report Class
Reporter.log(String s);
1. Reporter.log(String s);
This method logs the string passed into your HTML Report.
Parameters:
S - The message to be logged.
Parameters:
S - The message to be logged.
level - The verbosity of the message to be logged.
Parameters:
S- The message to be logged.
36
level - The verbosity of the message to be logged
logToStandardOut - Whether to print the message on standard output as well
Extent Reports
Extent Reports is an open-source HTML reporting library useful for test automation. Extent API can produce more
interactive reports, a dashboard view, graphical view, capture screenshots at every test step, and emailable reports.
Extent Report Maven Dependency -
Example
package ExtendReportsDemo;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
ExtentSparkReporter htmlReporter;
ExtentReports reports;
ExtentTest test;
@BeforeMethod
public void startReport() {
htmlReporter = new ExtentSparkReporter("ExtentReportDemo.html"); //(Report Name)
reports = new ExtentReports();
reports.attachReporter(htmlReporter); //We attached her htmlReport with report.
@Test
public void LaunchBrowser() {
//create test
test = reports.createTest("Launch browser and open url");
Assert.assertTrue(true); //test passed
}
@Test
public void VerifyTitle() {
//create test
test = reports.createTest("Verify Title");
Assert.assertTrue(false); //test failed
}
@Test
public void VerifyLogo() {
//create test
37
test = reports.createTest("Verify Logo");
Assert.assertTrue(true); //test failed
}
@Test
public void VerifyEmail() {
//create test
test = reports.createTest("Verify Email");
throw new SkipException("skipping this test case with exception");
}
@Test
public void VerifyUserName() {
//create test
test = reports.createTest("Verify User Name");
Assert.assertTrue(true); //test failed
}
@AfterMethod
public void getTestResult(ITestResult result) {
if(result.getStatus()==ITestResult.FAILURE) {
test.log(Status.FAIL, MarkupHelper.createLabel(result.getName()+ "FAIL", ExtentColor.RED));
}else if(result.getStatus()==ITestResult.SUCCESS) {
test.log(Status.PASS, MarkupHelper.createLabel(result.getName()+ "PASS", ExtentColor.GREEN));
}else if(result.getStatus()==ITestResult.SKIP) {
test.log(Status.SKIP, MarkupHelper.createLabel(result.getName()+ "SKIP", ExtentColor.BLUE));
}
}
38