You are on page 1of 38

TEST-NG FRAMEWORK

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 (@).

Features of Test-NG we can use in selenium

WebDriver has no native mechanism for generating reports. TestNG can generate the report in a proper &
readable format.

Multiple test cases can be grouped more easily.

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.

Annotations used in the testing are very easy to understand ex:

@BeforeMethod, @AfterMethod, @BeforeTest, @AfterTest.

Important Points on Test-NG

1. TestNG does not require you to have a main() method.

2. Methods need not be static.

3. We used the @Test annotation. @Test is used to tell that the method under it is a test case.

4. We needed to import the package org.testng.annotations.*.

5. We used the Assert class.

The Assert class is used to conduct verification operations in TestNG.


Assertions in TestNG are a way to verify that the expected result matches the actual result.
To use it, we need to import the org,testng.Assert package

Verify Page Title

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

//Launch chrome browser


WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
//Maximize the browser
driver.manage().window().maximize();
//open url
driver.get("https://www.google.com/");
String expectedTitle = "Google";
String actualTitle = driver.getTitle();

//Assert
Assert.assertEquals(actualTitle, expectedTitle);

//Close the browser


driver.close();

Test NG Example

package TestNG;

import org.testng.annotations.Test;

public class TestNGExample {

@Test
public void test1() {
System.out.println("Test Case 1");
}

@Test
public void test2() {
System.out.println("Test Case 2");
}
}

What is Test-NG XML File

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

Right click on package ⇒> TestNG = > Convert TestNG

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

Enable / Disable test cases


In TestNG, test cases can be enabled / disabled in two ways

You can disable the test case in a @Test annotation

TestNG @Test enable parameter

You can disable the test case in the XML file

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

public class LoanDepartment {

@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

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="BankSystem">
<test thread-count="5" name="CurrentAccount">
<classes>
<class name="TestNG.LoanDepartment">
<methods>
<exclude name="MobileLoginPersonalLoan"></exclude>
<include name="WebLoginPersonalLoan"></include>
</methods>
</class>
</classes>
</test> <!-- CurrentAccount -->
</suite> <!-- BankSystem -->

Annotations

What are TestNG Annotation


An annotation is a tag/ piece of code that provides additional information about the method. It is represented by
“@” prefix. It is used to control the execution of test cases

Following are some of the benefits of using annotations.

TestNG identifies the methods it is interested in, by looking up annotations. Hence, method names are not
restricted to any pattern or format.

We can pass additional parameters to annotations.

Annotations are strongly typed, so the compiler will flag any mistakes right away.

Test Annotation Attributes

@Test(description = “ ”)

package AnnotationAttributes;

import org.testng.annotations.Test;

7
public class Description {

@Test(description= "Mobile Application")


public void test1() {
System.out.println("Test Case 1");
}

@Test(description = "Web Application")


public void test2() {
System.out.println("Test Case 2");
}

@Test(description = "API Application")


public void test3() {
System.out.println("Test Case 3");
}
}

@Test(timeOut = 200)

package AnnotationAttributes;

import org.testng.annotations.Test;

public class TimeOut {


@Test(description= "Mobile Application")
public void test1() {
System.out.println("Test Case 1");
}

@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");
}

@Test(description = "API Application")


public void test3() {
System.out.println("Test Case 3");
}
}

package AnnotationAttributes;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

public class Demo {

@Test (timeOut = 200)


public void execution_Web_Application() {
WebDriverManager.chromedriver().setup();

WebDriver driver = new ChromeDriver();

driver.get("https://ultimateqa.com/dummy-automation-websites/");

driver.close();
}
}

@Test(dependsOnMethods = {”Method Name”, “Method Name”})

package AnnotationAttributes;

import org.testng.annotations.Test;

public class DependsOnMethod2 {

@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;

public class DependsOnMethod {

@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;

public class Priority {

@Test(priority=2, dependsOnMethods = {"b"})


public void a() {
System.out.println("A passed");
}
@Test(priority=0)
public void b() {
System.out.println("B passed");
}

@Test(priority=1)
public void c() {
System.out.println("C passed");
}

@Test(enabled = false)

@Test(groups = “group name”)

package AnnotationAttributes;

import org.testng.annotations.Test;

public class Groups {

@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");
}
}

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Group">
<test thread-count="5" name="Team">
<groups>
<run>
<include name="automobile"></include>
</run>
</groups>
<classes>
<class name="AnnotationAttributes.Groups" />
</classes>
</test> <!-- Team -->
</suite> <!-- Group -->

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.

Test NG Parameters (with XML Files)

Test NG Data Providers

Syntax : @Parameter({”parameter name”})

@Parameters({”param1”,”param2”,”param3”})

Ex1

package TestNG;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class TestParametersDemo {

@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;

public class TestDemo1 {


@Parameters("keysword")

10
@Test
public void search(String sdata) {
WebDriverManager.edgedriver().setup();
WebDriver driver = new EdgeDriver();

driver.manage().window().maximize();
driver.get("https://www.google.com/");

WebElement searchbox = driver.findElement(By.name("q"));


searchbox.sendKeys(sdata);

driver.quit();
}
}

<?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="AutoMobileTest">


<parameter name = "keysword" value = "Selenium"></parameter>
<classes>
<class name="TestNG.TestDemo1"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Test Data By Parameters


Keyword - 1) Selenium 2) Java
Test Steps :

Launch the browser and open www.google.com

Add the first Keyword as input in the search box

Verify the input value on UI to be same as from test data

Repeat the above two steps for the other 2 keywords.

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;

public class TestDemo1 {


@Parameters("keysword")
@Test
public void search(String sdata) {
WebDriverManager.edgedriver().setup();
WebDriver driver = new EdgeDriver();

driver.manage().window().maximize();
driver.get("https://www.google.com/");

WebElement searchbox = driver.findElement(By.name("q"));


searchbox.sendKeys(sdata);

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:

@Data Provider(name=”name of the data provider”)

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.

3. The Data Provider method returns a 2D list of objects.

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 :

1. Launch the browser top open www.google.com.

2. Search the first keyword combination.

3. Repeat the steps 2 for the other 2 keywords combination.

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;

public class DataProviderEx1 {


//1. India Qutub Minar
//2. Agra Taj Mahal
//3. Hyderabad Charminar

@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/");

WebElement searchbox = driver.findElement(By.name("q"));


searchbox.sendKeys(country + " "+ monument);
driver.findElement(By.name("btnK")).submit();
}
}

Sr.No Country Monument

1 India Qutub Minar

2 Agra Taj Mahal

3 Hyderabad Charminar

Parallel Testing

12
In parallel test case what we do?

Consider we have 3 methods

Method 1(); - 1 m

Method 2(); - 1 m

Method 3(); - 1 m

For execution to all 3 methods we have total 3 min.

We Can Execute

All the methods with @Test annotation will execute parallel.

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.

Parallel Test Demo (for title verify and Logo)

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;

public class ParallelTestDemo1 {


public WebDriver driver;
@Test
public void verifyTitle() {
//Launch browser
WebDriverManager.edgedriver().setup();
WebDriver driver = new EdgeDriver();

//Maximize
driver.manage().window().maximize();

driver.get("https://www.saucedemo.com/");

String expectedTitle = "Swag Labs";


String actualTitle = driver.getTitle();

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/");

WebElement logo = driver.findElement(By.xpath("//div[@class=\"login_logo\"]"));


Assert.assertTrue(logo.isDisplayed());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.quit();

}
}

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

Parallel Test Demo 2 (Verify login action)

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;

public class ParallelTestDemo2 {

@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/");

//find user name


driver.findElement(By.id("user-name")).sendKeys("standard_user");
//find password
driver.findElement(By.id("password")).sendKeys("secret_sauce");
//find login btn
driver.findElement(By.id("login-button")).submit();

Assert.assertEquals(driver.getTitle(), "Swag Labs");

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

driver.quit();
}

<?xml version = "1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name = "Suite" parallel = "classes" thread-count = "2">
<test name = "Test1">
<classes>
<class name = "TestNG.ParallelTestDemo1">
</classes>
</test>
<test name = "Test2">
<classes>
<class name = "TestNG.ParallelTestDemo2">
</classes>
</test>
</suite>

Listeners

What is Listeners in TestNG

14
Based on result on test cases what post action we need for that purpose we used Listeners. Listener is a
Interface

Types of Listeners in TestNG

1. IAnnotationTransformer.

2. IAnnotationTransformer2.

3. IConfigurable.

4. IConfigurationListener.

5. IExecutionListener.

6. IHookable.

7. IInvokedMethodListener.

8. IInvokedMethodListener2.

9. IMethodInterceptor.

10. IReporter.

11. ISuiteListener

12. ITestListener

I Test Listeners in TestNG

1. onTestStart(): An on TestStart() is invoked only when any test method gets started.

2. onTestSuccess(): An onTestSuccess() method is executed on the success of a test method.

3. onTestFailure(): An on TestFailure() method is invoked when test method fails.

4. onTestSkipped(): An on TestSkipped() run only when any test method has been skipped.

5. onStart(): An onStart() method is executed on the start of any test method.

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.

Listener Program Demo

public class ListenerDemo{


//Step 1 for integration is by annotations
@Listeners(TestNG.TestNG.ListenerClass.class)
@Test
public void login(){
WebDriverManager.chromedriver().setup();
//ChromeOptions class
ChromeOptions options = new ChromeOptions();
//argument for launch browser
options.AddArguments("--incognito");
//argument for maximize the browser
aoptions.AddArguments("--start-maximized");
//Launch browser
WebDriver driver = new ChromeDriver(options);
//Launch url
driver.get("http://orangehrm.qedgetech.com/symfony/web/index.php/auth/login");
//find locator for username
driver.findElement(By.id("txtUsername")).sendKeys("admin");
//find locator for password
driver.findElement(By.id("password")).sendKeys("admin123");
//find locator for login button
driver.findElement(By.id("btnLogin")).click();
//Verify title of dashboard by using assertion
Asserts.assertEquals(driver.getTitle(),"OrangeHRM");
driver.quite();
}

@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

public class ListenerClass implements ITestListener{

public void onStart(ITestContext Result){


System.out.println("On start method invoked............ ");
}

public void onFinish(ITestContext Result){


System.out.println("On finished method invoked");
}

//When Test Case get failed, this method is called.


public void onTestFailure(ITestResult Result){
System.out.println("Name of test method failed: " + Result.getName());
}

//When Test Case get Skipped, this method is called.


public void onTestSkipped(ITestResult Result){
System.out.println("Name of test method skipped: " + Result.getName());
}

//When Test Case get Stared, this method is called.


public void onTestStart(ITestResult Result){
System.out.println("Name of test method started: " + Result.getName());
}

//When Test Case get passed, this method is called.


public void onTestSuccess(ITestResult Result){
System.out.println("Name of test method sucessfully executed: " + Result.getName());
}
public void onTestFailedButWithinSuccessPercentage(ITestResult Result){

}
}

XML File

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suit name = "Suite">
<listeners>
<listener class-name = "TestNG.TestNG.ListenerClass.">
</listeners>
<test thread-count="5" name = "Test">
<classes>
<class name = "TestNG.TestNG.ListenerDemo" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

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/");

//find user name field


driver.findElement(By.id("user-name")).sendKeys("standard_user");

//find password field


driver.findElement(By.id("login-button")).sendKeys("secret_sauce");

//click on login button


driver.findElement(By.id("login-button")).click();

//verify after login dash board title


Assert.assertEquals(driver.getTitle(),"Swag Labs");

//closed the browser


driver.quit();
}

@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;

public class ListenerClass implements ITestListener {

public void onStart(ITestContext Result) {


System.out.println("On start method invoked...");
}

public void onFinish(ITestContext Result) {


System.out.println("On finished method invoked...");
}

//When test case get started, this method is called


public void onTestStart(ITestResult Result) {
System.out.println("Name of test method started: " + Result.getName());
}

//When Test Case get failed, this method is called


public void onTestFailure(ITestResult Result) {
System.out.println("Name of test method failed: " + Result.getName());
}

//When Test Case get skipped, this method is called


public void onTestSkipped(ITestResult Result) {
System.out.println("Name of test method skipped: " + Result.getName());
}

//When test case get passed this method is called


public void onTestSuccess(ITestResult Result) {
System.out.println("Name of test method successfully executed : " + Result.getName());
}
}

17
XML File

<?xml version ="1.0" encoding =" UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.dtd">
<suit name = "Suite">
<listeners>
<listener class-name = "TestNG.TestNG.ListenerClass"/>
</listeners>
<test thread-count="5" name = "Test">
<classes>
<class name = "TestNG.TestNG.ListenerDemo" />
</classes>
</test>
</suite>

Email able Report

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

What is Batch Testing

Running multiple test case in a suite is called 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.

In test NG we can use XML file to perform Batch Testing.

Test Scenario

Suite Test Case/ Class Test Methods

Sanity Test HomeScreen Test Launch Application()

VerifyTitle()

VerifyLogo()

Login Test LoginByMobileNumber()

LoginByEmail()

Functional Test Product Page Test AddProductToWishList()

AddProductToCart()

SelectQuantity()

PaymentTest CashOnDelivery()

NetBanking()

Batch Testing
HomeScreenTest

package BatchTesting;

import org.testng.annotations.Test;

public class HomeScreenTest {

@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;

public class LoginTest {

@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;

public class ProductPageTest {

@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;

public class PaymentTest {

@Test
public void CashOnDelivery() {
System.out.println("CashOnDelivery is passed");
}

@Test
public void NetBanking() {
System.out.println("NetBanking is passed");
}
}

XML file of Batch Testing


Sanity Testing

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

<?xml version="1.0" encoding="UTF-8"?>


<suite name="FunctionalTestSuite">
<test name="Functional Testing">
<classes>
<class name="BatchTesting.ProductPageTest" />
<class name="BatchTesting.PaymentTest" />
</classes>
</test>
</suite>

Master Suite

<?xml version="1.0" encoding="UTF-8"?>


<suite name="Master Suite">
<suite-files>
<suite-file
path="E:\New Eclips For Cucumber\My Eclipse program\DecemberBatch_TestNG_FrameWork\src\test\java\BatchTestin
<suite-file
path="E:\New Eclips For Cucumber\My Eclipse program\DecemberBatch_TestNG_FrameWork\src\test\java\BatchTestin
</suite-files>
</suite>

Assertions (Hard & Soft)

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.

Sr.No Methods Name Syntax

1 AssertEquals Assert.assertEquals(actual, expected,message)

2 AssertNotEquals AssertNotEquals(actual,expected, message);

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

1. Launch chrome browser

2. Open URL

20
3. Verify Title of the webpage

4. Verify the presence of the Wikipedia icon on web page.

5. Verify the presence of Wikipedia search button web page.

Hard Assert program

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;

public class AssertionDemo {

@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/");

System.out.println("Verify title ......... ");


String expectedTitle = "Automation Testing Practice";
String actualTitle = driver.getTitle();
Assert.assertEquals(expectedTitle, actualTitle,"Title is verify");

System.out.println("Verifying presence of wikipwdia-icon");


WebElement icon = driver.findElement(By.className("wikipedia-icon"));
//hard assertion
Assert.assertTrue(icon.isDisplayed());

//Verify the search button


System.out.println("Verify presence of wikipedia-search-button");
WebElement searchbtn = driver.findElement(By.className("wikipedia-icon"));
//hard assertion
Assert.assertTrue(icon.isDisplayed());

driver.close();
}
}

Soft Assert program

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;

public class AssertionDemo {

@Test
public void testMethod() {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
WebDriver driver = new ChromeDriver(options);

SoftAssert softVerify = new SoftAssert();


//open url
driver.get("https://testautomationpractice.blogspot.com/");

System.out.println("Verify title ......... ");

21
String expectedTitle = "Automation Testing Practice1";
String actualTitle = driver.getTitle();
softVerify.assertEquals(expectedTitle, actualTitle,"Title is verify");

System.out.println("Verifying presence of wikipwdia-icon");


WebElement icon = driver.findElement(By.className("wikipedia-icon"));
//hard assertion
softVerify.assertTrue(icon.isDisplayed());

//Verify the search button


System.out.println("Verify presence of wikipedia-search-button");
WebElement searchbtn = driver.findElement(By.className("wikipedia-icon"));
//hard assertion
softVerify.assertTrue(icon.isDisplayed());

driver.close();

//report all failure message


softVerify.assertAll();

}
}

Invocation Count

@Test anntation-invocationCount attribute

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;

public class InvocationCountDemo {

@Test(invocationCount = 5)
public void testMethod1() {
System.out.println("Test method1...");
}

public void testMethod2() {


System.out.println("Test method2...");
}
}

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="TestNG.InvocationCountDemo"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Now I want to know currently which invocation count is going execution

package TestNG;

import org.testng.ITestContext;
import org.testng.annotations.Test;

public class InvocationCountDemo {

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

//

file is a log4j configuration file

Step 1: Create src/main/resource

Log4j2.properties file or Log4j2.xml file


Paste these log4j2.properties or log4j2.xml in project home directory.
log4j2.properties file is a log4j configuration file.
which stores entire runtime configuration used by log4j.
location : src/main/resource

Log4j2.xml

<?xml version="1.0" encoding = "UTF-8"?>


<Configuration status = "WARN" strict = "true">
<Appenders>
<Appender type="Console" name = "STDOUT">
<Layout type = "PatternLayout"
pattern="%d{HH:mm:ss.SSS} [%t]%-5level %Logger{36} - %msg%n"/>
</Appender>

<Appender type = "File" name ="file" fileName="c:\temp\Log\app.Log">


<Layout type = "PatternLayout"
pattern="%d{HH:mm:ss.SSS}[%t]%-5Level %Logger{36} - %msg%n" />
</Appender>
</Appenders>

<Loggers>
<Root level = "all"/>
<AppenderRef ref = "STDOUT"/>

23
</Loggers>
</Configuration>

Steps for Log4j2.xml

This is also a configuration file having all runtime configurations used by log4j.

import log4j package

import org.apache.logging.log4j.*;

Create object of logger

Logger log = LogManager.getLogger(”ClassName”);

Log4j – Custom Log Levels

https://logging.apache.org/log4j/2.x/manual/customloglevels.html

Logger Demo Program

package Demo;
import org.apache.logging.log4j.*;

public class LoggerDemo{


public static void main(String [] args){
Logger log = LogManager.getLogger("LoggerDemo");
System.out.println("This is logger demo");
// if you want to lof any information or message then you can used
log.info("for info only");
log.debug("for debug");
log.error("for error message");
log.warn("warning message");

}
}

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

What is Page Object Model

Page Object Model (POM) is a design pattern, popularly used in test automation that creates Object Repository
for web UI elements

Under POM

Each web page is application

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

Implementation of Page Factory

with Page Factory

//using page factory


public class LoginPage2{
WebDiver driver;
LoginPage2(WebDriver d){
driver = d;

//this method will create


PageFactory.initElements(driver, this);
}
}

//identify web elements


//identify user name
@FindBy(id = "user-name")
WebElement username;

@FindBy(id="password")
WebElement password;

@FindBy(id="login-button")
WebElement loginBtn;

public void enterUsername(String uname){


username.sendKeys(uname);
}

25
public void enterPassword(String pwd){
driver.findElement(password).sendKeys(pwd);
}
public void clickOnLoginBtn(){
driver.findElement(loginBtn).click();
}

public class LoginTest{

public static void main(String [] args){


WebDriverManger.chromedriver().setup();
WebDriver driver = new ChromeDriver();

LoginPage2 lp2 = new LoginPage2();


driver.get("https://www.saucedemo.com/");

LoginPage2 lp2 = new LoginPage2(driver) ;


lp2.enterUsername("standard_user");
lp2.enterPassword("secret_sauce");
lp2.clickOnLoginButton();
lp2.closeBrowser();
}
}

without Page Factory

public class LoginWithOut{


public static void main(String[] args){
//Launch chrome browser
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

//open url
driver.get("https://www.saucedemo.com/");

//find & enter username


driver.findElement(By.id("user-name")).sendKeys("standard_user");

//find & enter password


driver.findElement(By.id("password")).sendKeys("secret_sauce");

//find & click on login button


driver.findElement(By.id("login-button")).click();
}
}

public class LoginPage{


WebDriver driver;

LoginPage(WebDriver d){
driver = d;
}

By username = By.id("user-name");
By password = By.id("password");
By loginBtn = By.id("login-button");

public void entUsername(String uname){


driver.findElement(username).sendKeys(uname);
}

public void enterPassword(String pwd){


driver.findElement(password).sendKeys(pwd);
}

public void clickOnLoginBtn(){


driver.findElement(loginBtn).click();
}
}

public class LoginTest{


public static void main(String[] args){

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

What is Cross Browser Testing

Cross Browser Testing (CBT) is a process to perform tests on multiple browsers.

This is done to know how a website performs on different browsers.

Cross-browser testing gives the confidence that the website behaviour is consistent across various
browsers.

Test Scenario

Verify the title of the google web page

Simple one

public class CrossBrowserTestingDemo{


WebDriver driver;

@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

<?XML version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1">
<suite name = "Suite">
<test thread-count="5" name="Test">
<classes>
<class name = "PackageName.ClassName">
</classes>
</test>
</suite>

For Multiple

public class CrossBrowserTestingDemo{


WebDriver driver;

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

XML for multiple

<?XML version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name = "Suite" parallel = "tests">
<test name="TestOnMSEdge">
<parameter name = "browser" value = "MSEDGE"></parameter>
<classes>
<class name = "PackageName.ClassName">
</classes>
</test>

<test name="TestOnChrome">
<parameter name = "browser" value = "chrome"></parameter>
<classes>
<class name = "PackageName.ClassName">
</classes>
</test>
</suite>

TestNG Retry Failed Test Cases

Why do we re-run the test case when it fails

There are multiple reasons why the test fails

Due to the network issue

Due to application downtime

Due to loading issue, etc

But if the script is failing due to XPath and some valid reason then you have to maintain for re work on your
scripts.

How We Re-run Failed Test Cases in Selenium In case of failure?

Using testing-failed.xml

RetryLogicDemo

package RetryLogicDemo;

public class TestCasesExample{

28
@Test
public void TestCasse01(){

Assert.assertTrue(false); //test case will fail


}

@Test
public void TestCasse02(){

Assert.assertTrue(false); //test case will fail


}

@Test
public void TestCasse03(){

Assert.assertTrue(true); //test case will pass


}
}

Using the IRetryAnalyzer interface that is part of TestNG We need to override the retry method.

RetryLogicDemo

public class RetryAnalyser implements IRetryAnalyzer{


//counter to keep track of retry attempts
int counterForRetryAttempts = 0;

//set max limit for retry


//Retry failed test cases for 3 times if they are failed 3 time then
//we can decleared as a failed.
int setMaxLimitForRetry = 3;

//Method to retry failed test cases


public boolean retry(ITestResult result){

if(!result.isSuccess()){
if(counterForRetryAttepts<setMaxLimitforRetry){

counterForRetryAttempts++;
return true;
}
}
return false;
}
}

package RetryLogicDemo;

public class TestCasesExample{

@Test(retryAnalyzer = RetryAnalyser.class)
public void TestCasse01(){

Assert.assertTrue(false); //test case will fail


}

@Test(retryAnalyzer = RetryAnalyser.class)
public void TestCasse02(){

Assert.assertTrue(false); //test case will fail


}

@Test(retryAnalyzer = RetryAnalyser.class)
public void TestCasse03(){

Assert.assertTrue(true); //test case will pass


}
}

XML

<?XML version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1">
<suite name = "Suite">
<test thread-count="5" name="Test">
<classes>
<class name = "RetryLogicDemo.TestCaseExample">
</classes>

29
</test>
</suite>

IAnnotationTransformer

RetryListener

import org.testng.IAnnotationTransformer;

public class RetryListener implements IAnnotationTransformer{

public void transform(ITestAnnotation testAnnotation, Class testClass,


Constructor testConstructor, Method testMethod){

testAnnotation.setRetryAnalyzer(RetryAnalyser.class);
}
}

XML

<?XML version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-1">
<suite name = "Suite">
<listeners>
<listener> class-name = "RetryLoginDemo.RetryListener"</listener>
</listeners>
<test thread-count="5" name="Test">
<classes>
<class name = "RetryLoginDemo.TestCaseExample">
</classes>
</test>
</suite>

RetryLoginDemo

package RetryLogicDemo;

public class TestCasesExample{

@Test
public void TestCasse01(){

Assert.assertTrue(false); //test case will fail


}

@Test
public void TestCasse02(){

Assert.assertTrue(false); //test case will fail


}

@Test(retryAnalyzer = RetryAnalyser.class)
public void TestCasse03(){

Assert.assertTrue(true); //test case will pass


}
}

What is HTTP Cookie

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.

Methods To Query and Interact with Cookies.

1. driver.manage().getCookies(); // Return the list of all Cookies


2. driver.manage().getCookieNamed(argO); // Return specific cookie Accorinding to name.
3. driver.manage().addCookie(argO); // Create and add cookies.
4. driver.manage().deleteCookie(argO); //Delete specific cookie.
5. driver.manage().deleteCookieNamed(argO); // Delete specific cookie Accoding Name.
6. driver.manage().deleteAllCookies(); //Delete all cookies.

Program on Cookies

30
Cookies Example

package CookiesDemo;

public class CookiesExample{


public static void main(String[] args){

//Launching the browser


WebDriverManage.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
//Add arguments
options.addArgument("--remote-allow-origin=*");

WebDriver driver = new ChromeDriver(options);

//Launch the url


driver.get("www.amezon.in");

//capture all the cookies


Set<Cooklist> cookiesList = driver.manage().getCookies();

//print size/ number of cookies


System.out.println(cookiesList.size());

//Enahance loop

for(Cookie ck : cookiesList){
System.out.println(ck.getName() + " " + ck.getValue());
}

// Close the browser


// driver.quit();

//get specific cookies according to name


System.out.println(driver.manage().getCookieNamed("i18n-prefs"));

//Create Cookie
Cookie cookieObje = new Cookie("TestCookie", "www.amazon.in");

//add cookie to browser


driver.manage().addCookie(cookiObje);

//capture all the cookies


cookiesList = driver.manage().getCookies();

//print size/number of cookies


System.out.println("After adding size:" + cookiesList.size());

for(Cookie ck: cookiesList){


System.out.println(ck.getName() + " : " + ck.getValue());
}

/*********************************************************************/

//delete cookie
driver.manage().deleteCookie(cookieObje);

//Capture all the cookies


cookiesList = driver.manage().getCookies();

//print size / number of cookies


System.out.println("\n\n After deleting " + cookiesList.size());

for(Cookie ck: cookiesList){


System.out.println(ck.getName() + " : " + ck.getValue());
}
}
}

What is Encoding / Encryption?

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;

public class EncodePasswordExample {

public static void main(String[] args) {


// TODO Auto-generated method stub

// //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=*");

WebDriver driver = new ChromeDriver(options);

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

How to Fill A form In A Single Statement By Using Actions Class.

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;

public class SingleStatement {

public static void main(String[] args) {


// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");

WebDriver driver = new ChromeDriver(options);

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

Actions act = new Actions(driver);


Action seriesOfActions = act.moveToElement(driver.findElement(By.id("user-name")))
.click()
.sendKeys("standard_user", Keys.TAB)
.sendKeys("secret_sauce", Keys.ENTER)
.build();
seriesOfActions.perform();
//
// driver.quit();
}

32
}

What is Data Driven Testing

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

Create a maven java project.

Navigate to Maven Central Repository.

Search for “Apache POI”

Add dependencies. poi

poi-ooxml

Click on Central tab and copy latest dependencies.

Paste above dependencies in pom.xml of your maven project and save it.

Data provider Program

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;

public class DataDrivenExample {

public static void main(String[] args) throws IOException {


// TODO Auto-generated method stub

//For the Excel file we used XSSF


XSSFWorkbook ExcelWBook = null;
XSSFSheet ExcelWSheet;
// XSSFRow Row;
// XSSFCell cell;

File excelfile = new File("D:\\15 December 2022 Batch\\TestNG FrameWork\\Test Data.xlsx");


FileInputStream inputStream = null ;

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

//to access the workbook sheet.


ExcelWSheet = ExcelWBook.getSheetAt(0);

//get total row count


int ttlRows = ExcelWSheet.getLastRowNum()+1;

//get total no. of cells in a row


int ttlCells = ExcelWSheet.getRow(0).getLastCellNum();

for(int currentRow = 0; currentRow<ttlRows; currentRow++) {


for(int currentCell = 0; currentCell<ttlCells; currentCell++) {

33
System.out.print(ExcelWSheet.getRow(currentRow).getCell(currentCell).toString());
System.out.print("\t");
}
System.out.println("\n");
}

ExcelWBook.close();

What is A Headless Browser


Headless Browser, means a Web Browser without User Interface. To elaborate, Headless Browsers are those which
actually access the web page, but the GUI / screen is hidden from the user.

Advantages Of Headless Browser

1. Headless Browsers are used when the machine has no GUI

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.

Disadvantages Of Headless Browser.

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.

For Chrome Browser

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;

public class ChromeHeadlessBrowser {

public static void main(String[] args) {


// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
options.setHeadless(true);
WebDriver driver = new ChromeDriver(options);

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");

//Enter log in button


driver.findElement(By.id("login-button")).click();

System.out.println("After login : " + driver.getTitle());


}

34
For Firefox Browser

For HTML

HTML Unit Driver

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

The TestNG will generate the default report

index.html

emailable-report.html

Reporter class - Used to log information in reports.

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;

public class TestNGReportExample {

@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

<?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="TestNG_Report_Demo.TestNGReportExample"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

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;

public class TestNGReportExample2 {

@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");

WebElement searchbox = driver.findElement(By.name("q"));


searchbox.sendKeys("india gate");
searchbox.sendKeys(Keys.ENTER);

driver.close();

}
}

Report Class

Report Class Syntax


Reporter Class of TestNg provides us with four different methods to log information.
Isn’t that interesting? Here are those methods:

Reporter.log(String s);

Reporter.log(String s, Boolean logToStandardOut);

Reporter.log(String s, int level);

Reporter.log(String s, int level, Boolean logToStandardOut);

1. Reporter.log(String s);
This method logs the string passed into your HTML Report.

Parameters:
S - The message to be logged.

2. Reporter.log(String s, Boolean logToStandardOut);


This method logs the string passed into your HTML Report.
Additionally, it also prints the same message on your HTML
Report if the current verbosity equals or is greater than the
one passed in the parameter.

Parameters:
S - The message to be logged.
level - The verbosity of the message to be logged.

What is Verbosity Level in TestNg?

The Verbose Level in TestNG is used to define the amount


of logging performed on the console. The verbosity level ranges
from 0 to 10, where 10 is the most detailed logging level
whereas 0 means minimal logging.

You can set the verbosity level in your testng.xml.


<suite thread-count="2" name="TestNGReporterTest" parallel= "classes" verbose="10">
1
<suite thread-count="2" name="TestNGReporterTest" parallel="classes" verbose="10">

4. Reporter.log(String s, int level, Boolean logToStandardOut);

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 -

<!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->


<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.0.9</version>
</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;

public class BasicExtendReportClass {

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.

//add envrionment detail


reports.setSystemInfo("Machine", "testpc1");
reports.setSystemInfo("OS", "window 11");
reports.setSystemInfo("user", "Ashish");
reports.setSystemInfo("Browser", "Chrome");

//configuration to change look and feel


htmlReporter.config().setDocumentTitle("Extent Report Demo");
htmlReporter.config().setReportName("Test Report");
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setTimeStampFormat("EEEE, MMMM dd, yyyy, hh:mm a'('zzz')'");
}

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

public void tearDown() {


reports.flush();
}
}

38

You might also like