0% found this document useful (0 votes)
4 views69 pages

Xpath Merged

The document provides a comprehensive overview of Xpath, JDBC, and automation testing methodologies. It covers Xpath syntax, functions, and types, as well as JDBC's role in database connectivity and automation testing scenarios. Additionally, it discusses the importance of generic utilities, object repositories, and the Page Object Model (POM) in optimizing test scripts and handling exceptions.

Uploaded by

abhilash gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views69 pages

Xpath Merged

The document provides a comprehensive overview of Xpath, JDBC, and automation testing methodologies. It covers Xpath syntax, functions, and types, as well as JDBC's role in database connectivity and automation testing scenarios. Additionally, it discusses the importance of generic utilities, object repositories, and the Page Object Model (POM) in optimizing test scripts and handling exceptions.

Uploaded by

abhilash gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Xpath:

It’s one of the locators in Webdriver tool, which is used to navigate to entire html

document & identify the object based on web element attribute & visible text [inner
text]

Xpath Symbols:

// → go to entire html document or else Go to descendant Elements

/ → traverse from parentHTMLTag to childHTMLTag

/.. → Traverse from childHTMLTag to parentHTMLTag

[] → provide tag backend attribute

@ → attribute symbol

* → match any htmlTag [regular expression]

Xpath Keywords:

And →match both the attribute

Or → match any one of the attributes

Xpath Functions:

Text ()

Contains ()

Normalize-space ()

Last ()

Xpath Axes:

1. self - current node

2. parent - immediate parent of current node

- //*[@attribute='value']/parent::tag

3. Child - immediate child of current node

- //*[@attribute='value']/child::tag

4. ancestor - parent's parent - grand parent with parent


- //*[@attribute='value']/ancestor::tag

5. descendant - child's child - grand child with child

- //*[@attribute='value']/descendant::tag

6. following - all the nodes after the current node

- //*[@attribute='value']/following::tag

7. following-sibling - current node to next sibling with same parent

- //*[@attribute='value']/following-sibling::tag

8. preceding - all nodes before current node

- //*[@attribute='value']/preceding::tag

9. preceding-sibling - current node to previous sibling with same parent

- //*[@attribute='value']/preceding-sibling::tag

Types of Xpath:

1. Absolute xpath

✓ Whenever xpath is written from root-Htmltag to child-Htmltag, followed by


/ is called absolute xpath.
✓ whenever we copy the xpath from inspect window, its automatically
generate Absolute xpath.
✓ Absolute xpath should not be used in real time selenium test, because it fails
to identify the same object, whenever object location or requirement is
getting changed.
✓ Syntax: //html/body/div..

2. Relative Xpath

✓ whenever xpath written directly to the webelement using webelement


attribute or visible text is called relative xpath.
✓ Relative will never get failed, even though object location / requirement is
getting changed.
✓ Because of Agile Methodology better to go for relative Xpath.
✓ Syntax://htmlTag[@attribute=’value’].
Different Cases to be followed while identifying the element using xpath:

1. Case 1: How to identify the object using One attributes

✓ Xpath is written directly to the element using unique attribute


✓ Syntax: //htmlTag[@attribute=’value’]
✓ Example: //input[@name='username']

2. Case 2: How to identify the object using multiple attributes

✓ when object not able to find the element using one attribute, we can go for
multiple attributes using and keyword.
✓ Syntax: //htmlTag [@attribute1=’value’ and @attribute2=’value’].
✓ Example: //input [@name='ck' and @type='checkbox'].

3. Case 3: How to identiy the object using visible text - text()

✓ If the text is written between start & end Tag is called Visible Text.
✓ text() is used to identify the object using visible text of the element.
✓ text() cannot identify dynamic text(the text which is changing dynamically).
✓ text() cannot identify the object using part of the string , because its complete
string matching function.
✓ it cannot ignore the space before & after the string.
✓ text() function navigate to html document & try to identify expected visible
text.
✓ in GUI, & return true if expected completely matches with UI text
✓ Syntax: //htmltag[text()='ExpectedValue']

//htmltag[.='ExpectedValue']

✓ Example: //h1[text()='Welcome']

4. Case 4: How to identify dynamic object - Contains ()

✓ contains function is used to identify the dynamic object.


✓ contains can automatically ignore the spaces before & after the string.
✓ contains function can identify the object using part of the string or complete
string.
✓ Syntax: //htmlTag[contains(text ()/@attribute, 'expected value')]
✓ Example: //h1[contains(text(),'users')]
5. Case 5: How to ignore unwanted spaces before and after the text - normalize-
space ()

✓ using normalize-space function we can ignore the space before & after the
String or attribute.
✓ Syntax: //htmlTag[normalize-space(text()/@attribute) = ‘expected
value’]
✓ Example: //h1[normalize-space(text())=’we have product’]

6. Case 6: how to identify the when similar/duplicate/same object present


multiple times in GUI

✓ When object not able to identify using multiple attributes, in such cases will
take reference of parent / grandparent htmlTag to identify the object
uniquely.
✓ Syntax: //parentHTmlTag[@att=’value’]/childHtmlTag[@att=’value’]
✓ Example: //div[@class='samsung']/input[@value='Add to cart']

7. Case 7: How to identify the elements using other element references

✓ Identify the reference [unique] element


✓ Identify the required Element
✓ Identify the common Parent for both required & reference Element
✓ Write html tree structure
✓ By taking a help of reference element try to traverse to requires element
✓ via common parent
✓ Also make use of various axes like ancestor, following-sibling, preceding-
sibling,decendant to optimse the xpath.
✓ Example: //span[text()='Apple iPhone 13 (128GB) - Midnight']

/ancestor::div[@class='a-section a-spacing-small a-spacing-top-small']

/descendant::span[@class='a-price']/span[@class='a-offscreen']

✓ Example: -//div[text()='REDMI 9i Sport (Coral Green, 64


GB)']/preceding::span[@class='f3A4_V']

8. Case 8: How to Identify Dynamic Elements - Dynamic Xpath

✓ Xpath is getting created during runtime is called Dynamic Xpath


✓ Dynamix xpath can be used to multiple elements by changing the variable
value in runtime.
✓ Dynamic xpath reduces size of Elements in Object Repository.
✓ In dynamic xpath variable value always comes from External File,but in
example variable value is hardcoded
✓ Example: //a[text() ='"+orgName+"'] -> Here OrgName is the dynamic Data

9. Case 9: Handling svg tags

✓ Svg elements are vector elements like graphical elements - circle, chrome
symbol firefox symbol where normal xpath format will not work
✓ Synatx for writing <svg> tags

//*[local-name()='svg']

identify twitter in test project

//*[local-name()='svg']/ancestor::li[@class='sc-twitter']
JDBC:
1. What are the steps to connect to database?
2. Explain JDBC architecture/Class diagram of JDBC?
3. What is real time usage of Finally block?
4. What are the advantages of JDBC?
 JDBC helps to connect any database from java program
 JDBC helps to automate preconditions
 JDBC helps to automate end to end scenarios
 JDBC helps for partial backend automation
 JDBC helps for database related validations
5. Why JDBC is required for Developers?
 Any Application should have its physical database to store the data
 Developers use JDBC to communicate with the database
 If java program has to connect with dB, then JDBC is like a bridge.
6. What is the use of JDBC for automation testers?
 JDBC is required to automate the pre conditions

Scenario: Test Scenario says we have to transfer 10000 rupees from account A
to account B. Pre-condition for above scenario is 10000 rupees should be preset in
account A.
If we know JDBC, we can connect to database via program and automate the
pre-condition also, this increases the number of automatable test cases.
 JDBC is required to automate End to end Scenarios.

Scenario: Test scenario says we have to add the product to the cart and verify if
the product is successfully added in the cart table of database. If we know JDBC,
we can connect to database via program and execute a select query and validate if
the data is present or not. This increases number of automatable scenarios.

MySqlDBcommands

 To create database: create database clientdb;

 To view all the databases present: show databases;

 To use the database: use clientdb;

 To create table inside the database:


create table clientinfo(name varchar(100), id int,address varchar(100));
 To check the table structure: desc clientinfo;

 To insert values into table


insert into clientinfo(name,id,address) values('Chaitra',12,'Banglore');

 To fetch the data from database: select * from clientinfo;


http://localhost:8888

Scenario 1:
Login to App
Navigate to Organizations
Create new Organization with mandatory details
Save and logout

Scenario 2:
Login to App
Navigate to Contacts
Create new contact with mandatory details
Save and logout

Scenario 3:
Login to Vtiger App
Navigate to Organizations link
Create organization with mandatory fields
Choose Healthcare in the Industry dropdown
save and logout.

Scenario 4:
Login to App
Navigate to Organizations
Create Organization with mandatory fields
Choose Electronics in industry drop down
Choose Investor in Type drop down
save and logout

Scenario 5:
Login to App
Navigate to Contacts
Create Contact with mandatory fields
Choose any existing organization
save and logout

Data Driven Testing: Automation rule says never hard code any data Store the
required data in any external resources and read that in the test script.
Common Data: data which is common to all the test scripts like URL, username,
password, browser name.
 Property File is more preferred
 Property File is light weight
 property file stores the data in key value pair
 Easy to read the data
Disadvantage: Not organized hence its preferred only for small amount of data

Test Data: data which is specific to only to the test case like
Create Organization -- Organization name
Create Contact -- Contact name
Create Contact with Organization -- Contact Name and Organization name
 To store test data, we prefer Excel sheet.
 excel sheet stores data in the form of rows and columns.
 Data is stored in a well-organized way so that data retrieval becomes easy.
 Data maintenance is easy.
 Disadvantage is Excel sheet is slow compared to property File.
Generic Library/Generic Utility/Generic Utils

 Generic utilities contain all the generic methods/re-usable method to


perform the action.
 No need to remember the syntax.
 All the methods written in generic utility are generic - generic method
 Generic methods are called functions were,
 if we want any data from the caller method, then parameterize it.
 if we have to give any data to the caller method then return it.
 the return type of generic method depends on the data type what we are
returning to caller.
 if we don’t return any data, then the default return type will be void.
 GenericUtility Package is created in src/main/java source folder.

Classes and interfaces written in Generic Utilities:

 To store all java related methods: JavaUtility - C


 To store all database related methods: DatabaseUtility - C
 To store all PropertyFile related methods: PropertyFileUtility - C
 To store all Excel File related methods: ExcelFileUtility - C
 To store all web driver related methods: WebDriverUtility - C
 To store all the constants: IConstantsUtility - I
 This is first stage of framework development
 usually, generic utilities are written by framework developers - 10+ year of
experience, 15+ year of experience like technical architects, automation
consultants, automation leads.
 Generic utilities are common to multiple projects also.

Advantages of Generic Utility

 No need to remember the syntax of web actions.


 Code reusability is achieved.
 Test script will be optimized.
 Code maintenance is easy.
 Time required for test script development is less.
 Debugging is easy.
 Generic Utilities can be used over multiple projects.
Object Repository/Element Repository:

✓ Automation rule says never hardcode and web element and its locator,
instead fetch it from an external resource.
✓ Object repository is a dedicated place to store all the web elements and their
locators.
✓ Object Repository can be designed with excel sheet, property file, Json File
and POM Class.
✓ Most preferred way of developing object Repository is POM Classes.
✓ Object Repository is stored in src/main/java.

Advantages of Object Repo

✓ Element and locator modification is easy.


✓ Frequent UI changes can be handled easily.
✓ No need to identify the same element multiple times.
✓ test script development will be faster.
✓ All the elements are stored in specific place hence maintenance will easy.
✓ Test script will be optimized.
✓ Code readability is increased.

What is POM?

✓ Java Design Pattern used to develop object repository as recommended by


google.
✓ POM classes are created Page wise and all the web elements are stored with
the help of rules of POM.
✓ Total number of POM Classes = Total number of web pages in your
application.
✓ All pom class name should be same as page name and appended with 'Page'
like LoginPage, HomePage, OrganizationsPage.

Why POM?

✓ It’s a Java design pattern, Java classes are created and utilized, hence no
external libraries are required.
✓ elements are directly available with the objects.
✓ POM is a perfect fit for Agile.
✓ POM will handle staleElementReference Exception.
Rules of creating POM Class

✓ Create a separate java class for a web page- class name should be same as
page name.
✓ Identify all the web elements present in a particular page with @FindBy,
@FindAll and @FindBys, and make it as private web element (Element
declaration)
✓ Initialize these web elements with a constructor and use
PageFactory.initElemnts(driver, this);(Element initialization)
✓ Provide getters to access these Elements - Encapsulation (Element
utilization)
✓ Provide business library to optimize the test script.

What is StaleElementReference Exception?

✓ it’s a selenium exception. whenever the browser is launched a driver


reference will be created.
✓ When selenium will try to identify the web element, it will be available on
GUI, but when selenium is executing the test script/performing action on the
web element, the element was no longer attached to the GUI due to page got
refreshed automatically,
✓ Element not attached to DOM during that execution, or element reference
might be Old.
✓ During these situations, selenium will throw StaleElementReference
Exception meaning the, Reference for that element is Stale or old.

How Does POM handle StaleElementReference Exception?

✓ POM will identify the web elements with annotations like @findby,
@findBys and @findAll instead of driver. FindElement ()/driver.
findElements ().
✓ And all the web elements identified will be initialized to driver current
reference with pagefactory. initElemnts(driver, this) or this.driver =
driver.
@Findby:

✓ It’s a selenium annotation.


✓ Will identify one element with one locator.
✓ @FindBy(name = "value")
✓ @FindBy(name = "user_name")
✓ private WebElement UserNameEdt;

@FindAll

✓ It’s a selenium annotation.


✓ @FindAll with identify a single web element with multiple locators.
✓ @FindAll({@findBy(name="user_name"), @findBy(id="userid")})
✓ private webElement userNameEdt;
✓ @FindAll works like OR operator (either this or That)
✓ Here the selenium will try to identify the user name element with name
locator if it’s not identified, then automatically it will retry to identify
the user name element with id locator. This process is called as Auto
Healing

Auto healing means: whenever the selenium fails to identify a particular element
with one locator, it will automatically retry the identification with other loactors.
hence @FindAll will provide Autohealing for test scripts.

@FindBys

✓ It’s a selenium annotation.


✓ @FindBys will identify a single web element with multiple locators.
✓ @FindBys({@findBy(name="user_name"), @findBy(id="userid")})
✓ @FindBys will work like a AND operator (both should be true)

What is encapsulation? How POM achieves encapsulation?

Encapsulation is hiding the data/ limiting access of a particular information


In POM, all the web elements are stored as private web elements, and only getter
access is provided through which setter access is denied. which makes the web
elements secure and no unnecessary changes in element locators are entertained.
This is how encapsulation is achieved.

-> @FindBy, @FindAll, @Findbys--> Cannot handle dynamic elements


✓ Because these annotation, will identify the elements before execution, All
dynamic elements should be handled with traditional method of
driver.findElement().
✓ In order to identify dynamic elements we can write dynamic xpath element
address/ xpath is updated dynamically during the run time

normal xpath -> //a[text()='ch399']

dynamic xpath for OrgName -> //a[text()='"+OrgName+"']

wipro200 -> //a[text()='wipro200']

Advantages of POM

1. Handles StaleElementReference Exception.

2. we can achieve encapsulation via POM.

3. POM is a java design pattern; no external libraries are required.

4. POM stores elements page wise, hence debugging is easy

5. Perfect fit for AGILE to handle frequent UI changes.

6. Code reusability.

7. Test script is optimized via business libraries.

8. Element and locator maintenance is easy.

9. Increased test script readability.


FRAMEWORK

Definition: Framework is a well-organized structure of reusable components


where one driver (.xml) file will take care of the execution without any manual
intervention.

Framework is collection of reusable components that makes automation


development execution and modification easier and faster.

Framework is a set of instruction followed by every organization that makes


automation test engineer life easy.

Types of Framework Approaches: Broadly There are two types of Framework


approaches:

1. TDD - Test Driven Development

 Test cases are mandatory.


 @Test is the driving factor for test script development.
 TestNG, Junit are used for any TDD approach-based framework.
 These Frameworks are easy to develop.
 Maximum number of features can be made re-usable.

2. BDD - Behavior Driven Development


 Test Scenarios are mandatory, anybody who has application knowledge can
write scenario
 @Given, @When and @Then are used for test script development
 Cucumber is the Tool used for BDD approach
 Given, when, Then, And are the Gherkins keywords which help to develop
the feature file, which is later used to develop the step definitions.
 Cannot achieve good code re usability.

3.TDD offers different types of Frameworks:

1. Data Driven Framework:

What? - reading the data from any external resources or using data provider is
called as data driven Framework. In Data driven framework, Data is the driving
factor.

Why? Automation rule says never hardcode the data, read it from external
resources.

When? whenever the test data is huge compared to test scenarios, we prefer
data driven framework.

Examples - Ecommerce, banking, Finance, Travel

2. Modular Driven Framework:


What? - Maintaining the test scripts, test data and suite xml file module wise in
order to make the debugging process easy is called as modular driven framework.
here module is the driving factor for framework.

Why? code Modification and maintenance is easy, Debugging is easy.

When? Whenever the application is very huge and has lot of modules, maintaining
all the modules together will be difficult, hence we prefer modular driven
framework.

Examples - CRM, SCM, Ecommerce, ERP

3. Method Driven Framework:

What? Developing the re-usable methods for all the repetitive


action/functionalities in the application and calling these methods in the test
script is called as method driven framework, here re-usable methods are the
driving factors for framework.

Why? Method re usability, Test script Optimization.

When? Whenever the application contains more repeated functionalities like too
many dropdowns too many frames, more windows, we prefer to write generic
method and use them multiple times.

Examples - Ecommerce, CRM, HealthCare


4. Keyword Driven Framework:

What? Creating a keyword library and utilizing these keywords to develop the
test script is called as keyword driven framework, here keywords are the driving
factors for framework.

why? if Non coder should perform automation/ freshers.

When? Whenever manual testers, Freshers, have to perform automation, they


would not be good at coding, hence we prefer Keyword driven framework where
all the actions are converted into methods with user friendly method names so
that they can just call and perform the actions.

Examples - short Term projects - Education, job portals.


5. Hybrid Framework:

What? Combination of two or more above discussed frameworks is called as


Hybrid framework.

Why? Some applications will have huge Data and also more number modules, so
we have combined feature of two framework to make the Framework user friendly.

When? - Whenever the application demands to use more than one framework we
use Hybrid by Combining the features of multiple frameworks.

NOTE: Hybrid = Data Driven + Modular Driven

Hybrid = Data Driven + Modular Driven + Method Driven ---

hybrid = Data Driven + Method Driven ---


Hybrid = Data Driven + keyword Driven

Hybrid = Data Driven + Keyword Driven + Method Driven

Examples - All long Term projects like Ecommerce, CRM, ERP, SCM .

Advantages of Framework:

 Test script development is faster and easier because of reusability


Modification and maintenance of data is easy because data is stored in
external resource.
 Modification and maintenance of element is easy because we have used.
 POM design pattern to maintain the elements in well-organized way.
 POM design pattern is the perfect fit for agile Process.
 Framework provide automatic screenshot for failed script.
 Framework provides flexibility to achieve cross browser testing,
distributed
environment testing, smoke testing, regression testing, regional regression
testing.
 Framework provide accurate execution report for every execution.
 Framework provides generic reusable utility for all actions like Excel Utility,
base class, database utility.
 Test script can be re used for every new build.
 Test script is optimized.

Disadvantages of Framework:

 Should be good in programming.


 Initial Framework development cost and time is high.

Phases of Framework: There are 3 phases in Frame work

Choice of Framework: In this Phase is based on CRS, technical leads, BA, PO,
automation Consultants will decide which type of framework should be chosen
then that framework design phase will start.

Framework design: In this phase framework developer will design the framework
which contain common utility like generic libraries, test data template, POM
classes with partial elements. This phase is executed in Sprint-1 or Release-1.

Framework Implementation: This phase starts from Sprint-2, all automation


engineer participates in test script development implementation.

Framework Execution: Execution phase is always handled by Jenkins tool, that is


whenever we get a new build to testing environment JENKINS will automatically
execute and send email to the concerned engineer.

Questions:

1. Explain Framework

2. Explain TDD framework

3. Explain TestNg framework

4. How your framework is hybrid justify.


TestNG - Test Next Generation

TestNg

 Is combination of JUnit and NUnit with some additional functionalities.


 TestNG is basically a Unit Testing Framework.
 Other Unit Testing Frameworks available in market are:

JUnit - Java

NUnit - .Net

PyTest/PyDev - Python

Rspsc - ruby

Jasmine/mocha - Javascript

TestNG - Java, .Net

TestNG usage for Developers:

Developers use TestNG as a Unit Testing Tool, where a test script is written to
test the source code of the application.

TestNG usage for Automation Testers:

Automation Testers use TestNG as a Unit Testing Framework for developing the
test scripts from manual test cases and executing them.

TestNG offers following annotations:

@Test

@BeforeMethod

@AfterMethod

@BeforeClass

@AfterClass

@BeforeSuite

@AfterSuite

@BeforeTest

@AfterTest
@DataProvider

@Listnener

@Parameters

Annotation:

 java template
 @
 meta data/ information to JVM
 No need to call

@Test:

 It’s a basic TestNG annotation which is responsible for all the executions.
 @Test acts like a main method for the JVM to start the execution.
 The return type of @Test annotation method is always void and access
specifier is always public.

@Test

public void demoTest ()

 We can have any number of @Test annotations inside a single Test class.
 Every @Test annotation is individual test script.
 Test class which consists of @Test annotations should be always written in
src/test/java in any package.
 Test class name should be always module name ending with Test.
 Test Method name should always be manual test case name with Test.
 In general, a Test class contains 15+ @Test annotations/Test Method.
 Default execution order of all the @Test annotations in a test class is
alphabetical/ASCII.
To Change the order of execution manually: Priority

@Test (priority = int)

 lowest priority executes First.


 Default value for priority is 0.
 priority accepts negative values also.

To run the same test script more than one Time: InvocationCount

@Test (invocationCount = int)

 Default value for invocation count is 1 -- By default @Test is executed once.


if we want to execute more than once, then we should specify the number of
times we want to run.
 Total number of times @Test is executed will be present in Total test runs.

@Test (invocationCount = 3, priority = 1)

 Always priority is given first preference while executing.

To make one @Test dependent on the status of another @Test:


DependsOnMethods

 @Test (dependsOnMethods = "createCustomerTest") - depend on status of


one method.
 @Test (dependsOnMethods {"createCustomerTest","modifyCustomerTest"})
- depend on status of more than one method.
 if we want to Execute any @Test depending the status - pass/fail of another
@Test then we can make the text script dependent on each other.
 In the below example, only createCustomerTest is passed,
ModifycCustomerTest and DeleteCustomerTest will be executed, if
createCustomerTest failed then both dependent test scripts will not execute
at all.
@Test

public void createCustomerTest ()

//Assert.fail();

System.out.println("customer created");//passed

} //failed

@Test (dependsOnMethods = "createCustomerTest")

public void modifyCustomerTest ()

//Assert.fail();

System.out.println("customer modified");

@Test (dependsOnMethods ={"createCustomerTest","modifyCustomerTest"})

public void deleteCustomerTest ()

Assert.fail();

System.out.println("customer deleted");

To Disable a test script: enabled = false

 whenever we want to disable a particular test script from current execution,


we use enabled.
 default value for enabled is true, if we make it as false then it will not be
included in the current execution
 @Test (enabled = false)
 By disabling the test scripts which are not impacted, we can reduce the
execution time and also, we avoid unwanted test scripts being executed
without deleting the test scripts/altering the test scripts.
To run the same test script multiple times with different set of Data:
DataProvider

 Data provider is an annotation which will load multiple data for every
execution.
 Total number of test runs = Total number of data present in Data
provider.
 Test class can have multiple @DataProviders but @Test can read only one
dataprovider at once.
 return type of @dataProvider annotation method is always Object [][].

sample program for DataProvider

public class DataProviderPractice

@Test (dataProvider = "phoneData") //-- read the data of data provider in test
script

public void addPhonesToCartTest (String name, int price)// store the data
in variables

System.out.println(name+" -> "+price);

@DataProvider (name = "phoneData") //--- create data provider and load the
values

public Object[][] getData()

{ //row //column count

Object[][] data = new Object[3][2];

data[0][0] = "Samsung A80"; // hardcoding

data[0][1] = 12000;

data[1][0] ="Iphone";

data[1][1] =5000;

data[2][0] = "Vivo";

data[2][1] = 1000;
return data;

@DataProvider (name = "brandData")

public Object[][] getData1()

{ //row //column count

Object [][] data = new Object[3][2];

data[0][0] = "Samsung A80";

data[0][1] = 12000;

data[1][0] ="Iphone";

data[1][1] =5000;

data[2][0] = "Vivo";

data[2][1] = 1000;

return data;

Real Time examples for usage of @DataProvider concept:

1.Add products into the cart - scenario is adding the product to the cart but we’ll
have Thousands of products to be added, here we have to execute this scenario as
many times as we have products. Hence data provider is a good option.

2. Create Multiple Users at a Time - here create user is a scenario, if we want to


create multiple users, we have to use data provider so that data is different
scenario is same.

3.@DataProvider: Test scenario is same but data is different

Total number of test runs = Total number of data used.

Basic Configuration Annotations - Return Type is void

@Test: Acts like a main method, which is identified by JVM to start the execution.
@BeforeSuite:

 It is executed before the <suite> tag in the suite xml file.


 It is executed only once per execution as there will be only one <suite>.
 It is used for establishing database connection.

@AfterSuite:

 It is executed after the closing of suite tag </suite> in suite xml file.
 It is executed only once per execution as there will be only one </suite>.
 It is used for closing database connection.

@BeforeTest:

 It is executed before the opening of <Test> in suite xml file.


 The number of times it will execute depends on number <Test> tags.
 This is mostly used for parallel executions as it creates multiple threads.

@AfterTest:

 It is executed after the closing of test tag </Test> in suite xml file.
 The number of times it will execute depends on number </Test> tags.
 This is mostly used for parallel executions as it creates multiple threads.

@BeforeClass:

 It will execute before opening of every class <class> in suite xml file or
simply we can tell before every test class.
 The number of times it will execute depends on the number of <Class> or
Test class.
 It is used for launching browser.

@AfterClass:

 It will execute after closing of every class </Class> in suite xml file or
simply we can tell after every test class.
 The number of times it will execute depends on the number of </Class> or
Test class.
 It is used for closing browser.

@BeforeMethod:

 It will execute before every @Test annotation.


 The number of times it will execute depends on number of @Test.
 It is used for login to Application.
@AfterMethod:

 It will execute after every @Test annotation.


 The number of times it will execute depends on number of @Test.
 It is used for logout of Application.

BaseClass:

 It consists of all basic configuration annotations with specific functionality.


 Base class is designed in Generic Utility Package of src/main/java.
 There will be only one base class for a project.
 All the test scripts should extend from base class to inherit the
functionalities written inside the base class.
 Automation rule says "all test script should extend from base class".
 Base class will be usually designed by framework developer.
 Once after the generic utilities are configured, Object repository designed
later, base class is configured.
 once both generic Utility and Object Repo are ready, Framework design is
completed
 This framework will be shared amongst all the automation engineers in the
team, and they will start contributing the test script with the help of
Framework.
 Single base class acts as a parent and all the test scripts act as individual
child’s.
 Hence base class follows "hierarchical Inheritance”: Inheritance real
time example.

Explain inheritance with respect to your framework:

We use inheritance in Base class which follows hierarchical Inheritance where


base class contains all the basic configuration annotations will act as a parent
class and all the test script should extend from Base class to utilize the
functionalities given in base class.

Advantages of BaseClass:

 Code re usability.
 Test script is optimized.
 No need to invest time on unwanted actions.
 Test script development is faster.
 Code maintenance and modification is easy.
 Debugging process is easy.
TestNG Executions

Execution: Once the test scripts are developed, they have to be executed to check

the correctness of the code - running the program.

Validation: Whether the result is as expected or not.

NOTE: For every new feature/build, we will execute the recent/old Framework
to check the regression issues.

Batch Execution:

 Executing all the existing test script sequentially/one after another.


 Batch execution is also called as FULL REGRESSION testing.
 All the test scripts are loaded inside one suite xml file.
 In one suite xml file / testNg.xml file we can invoke any number of classes
but all the classes should be present inside the project.
 All the class names should be provided as qualified class name

packageName.Classname<classname="vtiger.ContactsTests.CreateContactWit
hOrgTest"/>

 Preserve-Order = "true" is a feature in <test>


<test thread-count="5" name="Test" preserve-order="true">
if it’s true -> Execution order will be same as classes are loaded
if its false -> Execution order will be alphabetical
 Batch execution is preferred to perform full regression testing that is
when we cannot identify the impacted areas, or all the areas impacted,
Batch Execution is preferred.

Group Execution:

 Executing the similar kind of test script under a group ex: smokeSuite,
RegressionSuite.
 All type test script belongs either to smoke suite or to Regression suite
 To achieve group execution, Every @Test should be included in the group

@Test (groups = "RegressionSuite")

@Test (groups = {"SmokeSuite”, “RegressionSuite"})


Groups should be specified in 3 places:

1. @Test

In test script @Test (groups = "RegressionSuite")

2. Base Class

@BeforeSuite (groups = {"SmokeSuite”, “RegressionSuite"})

3. suite xml file

<Suite>

<groups>

<run>

<include name="SmokeSuite"></include>

</run>

</groups>

<test thread-count="5" name="Test">

<classes>

<class name="vtiger. ContactsTests.CreateContactWithOrgTest"/>

<classname="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

</classes>

</test> <!-- Test -->

</suite> <! -- Suite -->

Smoke Suite:

Smoke suite consists of all the test scripts which are identified as smoke
scenarios/test script related to critical features.

<groups>

<run>

<include name="SmokeSuite"></include>

</run>

</groups>
Regression Suite:

All the test scripts which are considered as impacted scenarios are grouped under
Regression suite. This will be updated for every build dependending on impacted
areas. Usually, Developers will tell the areas which are impacted.

<groups>

<run>

<include name="RegressionSuite"></include>

</run>

</groups>

1.Regional Regression Suite:

It is used when we exactly know which test script is affected/impacted in the


test class, then directly we can go to the suite xml file and include only that
method and execute.

<suite name="Suite">

<test thread-count="5" name="Test">

<classes>

<class name="vtiger.ContactsTests.CreateContactWithOrgTest">

<methods>

<include name="demoRegregression"></include>

</methods>

</class>

</classes>

</test> <! -- Test -->

</suite> <! -- Suite -->

Parallel executions

Parallel execution means multiple threads start the execution simultaneously.

 Distributed Parallel execution


 Cross Browser Parallel Execution
 Cross Platform Parallel Execution
Distributed Parallel execution:

 We prefer distributed parallel execution when we have to reduce the total


execution time taken by a suite.
 We distribute the total number of existing test scripts among multiple
threads in Suite xml file with <test> and start the execution.
 Browser will not be changed here. Only the test scripts are distributed.
 Different threads - Different test scripts - Same browser launched in all
threads.
 One thread can have any number of test classes and all the test class inside
the <test> and </test> will be executed Sequentially.

<suite thread-count="2" parallel="tests" name="Suite">

<test thread-count="2" parallel="tests" name="Test-Runner-1">

<classes>

<class name="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

<class name="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

<class name="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

<class name="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

<class name="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

<class name="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

</classes>

</test> <!-- Test -->

<test thread-count="2" parallel="tests" name="Test-Runner-2">

<classes>

<class name="vtiger.ContactsTests.CreateContactWithOrgTest"/>

<class name="vtiger.ContactsTests.CreateContactWithOrgTest"/>

<class name="vtiger.ContactsTests.CreateContactWithOrgTest"/>

<class name="vtiger.ContactsTests.CreateContactWithOrgTest"/>
<class name="vtiger.ContactsTests.CreateContactWithOrgTest"/>

<class name="vtiger.ContactsTests.CreateContactWithOrgTest"/>

</classes>

</test> <!-- Test -->

</suite> <!-- Suite -->

 @BeforeTest and @AfterTest can be used to launch the browser and close
the browser.
 Instead of @BeforeClass and @AfterClass if launching browser action is
needed at <test> in the suite xml file like:

@BeforeTest

//@BeforeClass(groups = {"SmokeSuite","RegressionSuite"})

public void bcConfig()

//--launch the browser--

How do achieve Distributed Parallel Execution?

 Distributed Parallel execution is a form of TestNg executions which is used


to reduce the execution time required when all the test scripts are
executed as Batch.
 We will create a separate suite xml file and give parallel mode as Tests
and provide required thread count (max thread count is 5).
 Later create a separate <test> </test> and load the required classes which
should execute in different threads.
 Run the execution.

Cross Browser Execution/Compatibility Testing:

 Cross browser execution means executing the same set of test scripts in
multiple browsers to ensure they are compatible.
 In cross browser execution, same set of test scripts are executed over
different browsers in different threads.
 Different Threads - Different Browsers - same set of Test scripts.
 Since during run time we have to choose the browser for execution, we have
provide browser name from suite xml file instead of property file.
 <Parameter> is used to set the name and value which will pass this data to
@Parameter annotation in base class.

In suite xml file:

<suite thread-count="2" parallel="tests" name="Suite">

<test thread-count="2" parallel="tests" name="Test-Runner-Chrome">

<parameter name="BROWSER" value="Chrome"></parameter>

<classes>

<class name="vtiger.ContactsTests.CreateContactWithOrgTest"/>

<class name="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

</classes>

</test> <!-- Test -->

<test thread-count="2" parallel="tests" name="Test-Runner-Firefox">

<parameter name="BROWSER" value="Firefox"></parameter>

<classes>

<class name="vtiger.ContactsTests.CreateContactWithOrgTest"/>

<class name="vtiger.ContactsTests.CreateContactWithMandatoryFieldsTest"/>

</classes>

</test> <!-- Test -->

</suite> <!-- Suite 

In BaseClass:

@Parameters("BROWSER")

@BeforeTest

//@BeforeClass(groups = {"SmokeSuite","RegressionSuite"})

public void bcConfig(String BROWSER) throws IOException


{

//String BROWSER = pUtil.readDataFromPropertyFile("browser");

String URL = pUtil.readDataFromPropertyFile("url");

if(BROWSER.equalsIgnoreCase("CHROME"))

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver();

Reporter.log("--Browser "+BROWSER+" launched successfully-


-",true);

How do perform Cross browser execution/compatibility Testing?

 Choose the test scripts which have to execute in multiple browsers.


 create a separate suite xml file and choose parallel mode as tests and set
thread count as required.
 create separate <test> and load the same class in both threads.
 Provide browser details using <parameter>
<parameter name="BROWSER" value="Firefox"></parameter>
 Use @Parameters annotation to read the parameter value from suite xml
file in base class.
@Parameters("BROWSER")
 Parameterize annotation method to capture the browser details
public void bcConfig (String BROWSER) {}
 Execute/run the test script through suite xml file.

How do you read data from suite xml file to your test script?

How do achieve data driven testing with suite xml file?


 we have to use <parameter> in suite xml file and provide name and value.

<parameter name="BROWSER" value="Firefox"></parameter>


 That data we have to capture in test script using @Parameters annotation
Parameters("BROWSER").

Assertions

 Automation rule says Validation is mandatory for every test script.


 Validations are very important part of test script development which is
completely depended on individual automation engineering.
 Every test script should be validated for the correctness of result based on
expected and actual result.
 Java If-Else blocks are not recommended for validations of test script as if-
else block do not have the capability to fail the test script.
 Depending on if condition:

if true: if block will be executed

if false: else block will be executed.

 So, no failure will occur and since in any case either If or Else is getting
executed, further lines in the test script will be executed. Hence this
validation is not recommended.

Assertions is a feature of TestNG which helps in validation. if expected result


doesn’t match with actual result, Assertions will give Assertion Error
Exception and fail the test script providing the line no of the failure.

Hard Assert:

 Class name is Assert.


 All the methods present here are static methods hence accessed via Class
name.

Assert.assertTrue();

Assert.assertFalse();

Assert.assertEquals();

Assert.assertNotEquals();

Assert.assertNull();

Assert.assertNotNull();
Assert.fail(): These are the few methods present in Assert Class.

 Hard assert will stop the execution of further lines if the assertion is failed.
 Whenever hard assert test script fail, hard assert will generate Assertion
Error Exception along with line number of failure and error message and it
will stop the current test script execution and continue other test scripts in
the same test class.
 Whole test script gets failed if one hard assert is failed.
 Hence Hard assert is used to validate mandatory fields in the test script.

Soft Assert:
 Class name is SoftAssert.
 All the methods present here are non-static methods hence accessed by
creating object.

SoftAssert sa = new SoftAssert ();

sa. assertTrue ();

sa. assertFalse ();

sa. assertEquals ();

sa. assertNotEquals ();

sa. assertNull ();

sa. assertion ();

sa. fail ();

sa. assertAll ();

These are the few methods present in SoftAssert Class.

 Soft assert will not stop the execution of further lines if the assertion is
failed.
 Whenever soft assert test script fail, soft assert will generate AssertionError
 Exeception along with line number of failure and error message and it will
continue the current test script execution.
 assertAll () is a special method which will sum up the status of all soft
asserts used in the entire test script and provide it in console at the end.
 if assertAll () is not used at the end of all soft assert statements, no failures
will be logged.
 Hence Soft assert is used to validate non mandatory fields in the test script.

Interfaces in TestNG

ITestListener:

 It is an inbuilt interface available in TestNG

 ITestListener has abstract methods which will capture all the run time events
of a test script like Pass, fail, Skip.
 As per the rule Listener Implementation class should implements ITestListener
Interface and should override all the abstract methods present.

 Some of the imp abstract methods are:

1. onStart() - Start of current suite execution

2. onFinish() - end of current suite execution

3. onTestStart() - start of current test script execution (@Test)

4. onTestSucecss() - current test script execution is passed (@Test)

5. onTestFailure() - current test script execution is failed (@Test)

6. onTestSkipped() - current test script execution is skipped (@Test)

 Listener Implementation is a class created in GenericUtility package of


src/main/java is used to receive the event status from @Listeners annotations
present in every testscript class and then perform appropriate action based on
result (pass and fail).

 In Framework, as listeners will monitor the test script execution, we configure


the extent Reports using listeners.

 onTestFailure() is implemented to take the screenshot when ever the test


script is getting failed.

 @Listeners(vtiger.GenericUtility.ListenerImplementation.class) - will
communicate with ListenerImplementation class and monitor the test script.

ITestResult:
It is an interface available in TestNG and it is used as an argument for every
abstract method in Listener implementation class which will capture the pass/fail
status of the current test script during run time.

IRetryAnalyser

 Its an interface present in TestNG, which will help us re run the failed test
script.

 Sometimes failures can be due to synchronization issues, network issues,


server issues or any miscellaneous issues. and if we run the script for 3 or 4
times the test script might pass.

 For these kind of situation we will manually analyse it, make sure there is no
script issue or its not a bug, then we try to rerun for couple of times, if passed
only then for the next execution we will implement retry anaylser.

 Provide an implementation class for IRetryAnalyser interface in GenericUtility


package and implement the retry().

 To use retry analyser in test script.

@Test(retryAnalyzer = vtiger.GenericUtility.RetryAnalyserImplementation.class)

Questions:

1. Should we provide listeners to every class?

Yes. we have to provide listeners for every class because each class should be
monitored

@Listeners(vtiger.GenericUtility.ListenerImplementation.class)

Listeners can be given at Suite xml file also

<listeners>

<listener class-
name="vtiger.GenericUtility.ListenerImplementation"></listener>

</listeners>
2. Should we provide retry analyser for every @Test?

No. we have to first analyse the failed test scripts, if we found they are passed
after couple runs, we should decide retry count and only for those test scripts we
will implement retry analyser.

@Test(retryAnalyzer = vtiger.GenericUtility.RetryAnalyserImplementation.class)

3. Why Listeners?

Listeners is a feature in TestNG used to monitor the run time every of a test script
and based on the events, we can perform necessary actions with abstract methods
of ITestListerner interface.
1. We can capture run time events

2. we can configure extent reports

3. It provides inbuilt methods to log the status of test script

4. Why We have take screenshots?

 Screen shots act as a proof to the developer for rising the defect/bug.

 Debugging becomes easy with screenshot.

 It can be shared across with developer and other tester for easy
communication of the issue.

5. Out of 1000 test script, 200 test scripts got failed. How do you re run only
the failed test scripts?

In Project -> test Output folder -> testng-failed.xml

This suite xml file will consists of failed test scripts in the current execution and it
is auto updated. if we run this suite xml file, all the failed script in current
execution will run.

6. Out of 1000 test script, 200 test scripts got failed. What is your approach?

 First check the execution report.

 re run the failed test scripts to analyse the issue like wat is the exception line
no.

 put break point and run the individual test script in debug mode.

 if it is a test script issue - correct it and update the framework.

 if it is a product issue - rise it as a bug.


Reports:

 Reports are a very important part of Framework because they act like proof for
all the execution done by automation tester.

 Customers usually ask for execution report.

 Reports have to be provided for Developers also.

 Usually after every execution reports will be sent to high offs like product
Owner,Automation Leads, Technical consultants and customers.

There are two types of reports:

High Level Reports: TestNG supports HTML report which provides basic
information like

 Total number of test scripts executed

 Number of test scripts Passed/failed/Skipped

 reason for the failure.

Low Level Reports: These specify the log level analysis,In TestNg we have
"Reporter.log();"

Different log levels:

- INFO - which will give information

- WARNING - warning

- ERROR - issue

- FATAL - issue

Disadvantages of HTML reports in TestNG:

 No Pie Chart representation

 Non customisable.

 Cannot attach screenshots.

 Very simple reporting format.

 In order to over come these, we use EXTENT REPORTS or ALLURE REPORTS.


Extent Reports:

It a popular reporting format used in several companies as it given graphical

representation of high level report

IT has 3 major classes

ExtentSparkReporter:Used to set the basic configuration for the report

ExtentReports: its a main class which will set system information to the report

ExtentTest : This class will perform test script level analysis.

 Extent reports can be configured in BaseClass or ListenerImplementation class


of genericUtility package in framework. most prefered is
ListenerImplementation Class as it monitors the execution.
 flush() should be mandatorily used at the end which will consolidate all test
execution status and generate the report.
MAVEN

Its also called as Build management Tool, Build testing Tool, Build Dependency
Tool,Maven is Tool used which has become popular for the build management
instead ANT and GRADLE.

Why Maven used in Development?

 In case of Development Maven is used as Build Process Tool [Build creation,


Build testing and Build Deployment].

 Various Maven commands are used for these build related actions like

Build Creation process: Process of converting the source code into any
executable format “mvn package” is the maven command used.

Build Testing Process: Since multiple Developers will be contributing to the


projects, We have to test the project for compilation issues, or/and if the build is
broken or not."mvn Compile", "mvn Test" is the maven command is used.

Build Deployment Process:Process of installing the build into Testing


server/any other Environment,"mvn Deploy","mvn install" is the maven
command is used.

Why Maven used in Automation Testing?

 In Automation Maven is used for Testing the Application with the


current/recent Framework by executing the test scripts

 When Multiple automation testers are working with same framework, there
might be chances that the changes made by one Automation engineering might
affect the entire framework, in order to over come this issue we run the Maven
life cycle for every build mvn clean, mvn validate, mvn compile, mvn test
are the maven command used.

Softwares in Maven:

Maven Eclipse Plugin: This is inbuilt plugin available when in eclipse. It helps to
create Maven project and provides folder structure as

To create maven Project:

Group id: Organization/Community Name

Artifact Id: Project Name


Inside Maven Project: Framework folder structure

src/main/java

 GenericUtilities

 ObjectRepository

src/main/resources

 ChromeDriver.exe

 FirefoxDriver.exe

 IEDriver.exe

src/test/java

 autodesk.OrganizationsTests

 autodesk.ContactsTests

src/test/resources

 commonData.properties

 TestData.xlsx

pom.xml

 Dependencies

 plugins

pom.xml:

 Its called Project Object Model or Project Configuration file.

 Its the heart of any maven project.

 Its created only once during the project creation.

 If pom.xml is corrupted, then we have to discard the entire project and create
another.

 The components of pom.xml are dependencies and Plugins.

Dependencies in Maven

Dependency is advance feature in maven which is used to get all the required

jars from the Global repository(http://mvnrepository.com) to Local repository


(C://user/name/.m2) & attach all jars to the project automatically.

<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>3.141.59</version>

</dependency>

Maven Cmd Line Plugin:

 This is a Maven software which helps us to run the maven project without
eclipse.

 we have to download Maven to local system and set the environment variables.

 To check if its set properly: <cmd>mvn --version.

Build Life Cycle/maven Life cycle:

mvn clean:Its a maven command used to clean all the old reports from target
folder.

mvn validate:Its a maven command used to check if all the necessary jar are
downloaded for all the dependencies added, if not it will automatically download.

mvn compile: Its maven command to will check the compilation issues in the
framework.

mvn test: Its a maven command which will identify all the test classes whose
class name end with "test" and execute them.

To execute the test script in command line:

1. Go to the current project location where pom.xml file is present in your local
system.

2. invoke command prompt from project location

D:\MavenProjects\Com.ERP.Resource>

3. execute the maven life cycle commands and verify

mvn test:

 At class level, if no testNg.xml file is there,All the classes in the project whose
name end with "test" will get executed
D:\MavenProjects\Com.ERP.Resource>mvn test

At Suite Level,

 It will run the testNg.xml file loaded in surefire plugin of pom.xml

D:\MavenProjects\Com.ERP.Resource>mvn test

To run specific test class through cmd line:

mvn -Dtest=className test

 It will navigate to project location compare all the test class name with the
name given in the command if its matching it will execute.

 Here -D stands for data , if we want pass any data through maven command
we use -D.

 whenever we want load particular class name -Dkey=value syntax should be


followed and key is always test and value can be any class name

ex: mvn -Dtest=OrganizationTest test

 cmd used is: D:\MavenProjects\Com.ERP.Resource>mvnDtest=className


test.

To execute more than one class through command line

multiple class names can be given separated by comma

 -Dtest=OrganizationTest,ContactTest

 -cmd used is:


D:\MavenProjects\Com.ERP.Resource>mvnDtest=OrganizationTest,Contac
tTest test

To run a spefic test method / @Test inside a particular class

 when a test class consists of multiple test methods/@Test and we have run

particular test method then we make use of # and specify the method name

-Dtest=ClassName#methodName.

cmd used is:


D:\MavenProjects\Com.ERP.Resource>mvnDtest=OrganizationTest#cre
ateOrgTest test
To pass data from cmd line: Maven Parameters

 When we get a situation to provide run time parameters, then we have to use
Maven parameters as -Dkey=value format.

ex: we can pass the browser name and url through cmd line as

-Dbrowser=Chrome -Durl=http://localhost:8888

 Using maven parameters we can pass any data during the run time.

 To perform any actions, we have to use system.getProperty("key") in the test


script.

 When ever we want to provide run time parameters through eclipse we use vm
arguments in run configurations.

 Right click on test script -> run As -> Run configurations -> Arguments -> VM
arguments type the below command.

-Dbrowser=Chrome -Durl=http://localhost:8888

 Through cmd line we can provide runtime parameters using below cmd:

 D:\MavenProjects\Com.ERP.Resource>mvn-Dbrowser=Chrome
Durl=http://testEnv.com-Dusername=admin-
Dtest=ReadDataFromCmdLineTest test.

Question:

1. How do you read data from cmd line to your test script?

 We have to make use of Maven parameters, like -Dkey=Value

 what ever data we want to provide like browser name, username, password
url etc

 we can provide with the below command.

mvn -Dbrowser=Chrome -Durl=http://testEnv.com -Dusername=admin -


Dtest=ReadDataFromCmdLineTest test
2. Why do you have to read data from cmd Line?

 Sometimes we can get a situation where the customer would want to execute
the test script with different browser, or in different environment or with
different credentials, so since customer cannot go and make changes in the
framework, we provide an option in the framework to accept run time
parameters so that we can pass the data using maven parameters through
cmd Line.

 To run any TestNG.xml file (suite xml file) through pom.xml: Surefire Plugin.

 In reality we will be having various suite xml files for every execution type like

testNG-Batch.xml ---------------------To run all the test classes sequentially

testNG-SmokeSuite.xml ----------------To run only smoke scenarios

testNG-RegressionSuite.xml -----------To run only regression scenarios

testNG-RegionalRegressionSuite.xml ---To run only impacted test script

testNG-DistributedParallelSuite.xml --To run Batch in multiple threads

testNG-CrossBrowserExecution.xml -----To run same set of scripts in


different browsers

 So we cannot run the test scripts class wise, we have to run the test script
based on suite xml files.

 Also by mistake if any class name is not ending with "test", then maven will
not identify it as a test class and do not include it in "mvn test".

 Hence to load testng.xml file we make use of a plugin called as "SUREFIRE"


SureFire plugin will load the relevent testNG.xml file in <suiteXmlFile> and this
testNG.xml file is recognised by maven while executing mvn test.
<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<version>3.0.0-M7</version>
<configuration>

<suiteXmlFiles> <!--This testng.xml file will be executing in cmd


prompt if we give mvn test -->

<suiteXmlFile>testng_SmokeSuite.xml</suiteXmlFile>

</suiteXmlFiles>

</configuration>

</plugin>

</plugins>

</build>

To run specific suite xml file when there are multiple suite xml file: Maven
Profiling

 SureFire plugin allow us to read testNG.xml via pom.xml.

 If we have to load different testNg.xml file then we have make changes in


surefire plugin <suiteXmlFile> which is not recommended as many times
making changes in pom.xml, might corrupt the pom.xml file. If it happen then
we have discard the entire project.

 Hence we will create a separate profile for every suite xml file in pom.xml and
in maven cmd we will call the specific profile by its profile id.

maven cmd is :

mvn test -P profileId --> here -P stands for profile.

 Sample profiles:

<profiles>
<profile>
<id>Smoke</id> <!-- This is profile id -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng_SmokeSuite.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>Fail</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng-failed.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
Maven command to run Smoke profile

mvn test -P Smoke

NOTE: A separate profile for testNg-Failed.xml file will also be created to run only

the failed test scripts.mvn test -P Fail

Advantages of MAVEN

 Check the integration & compilation issue between the framework component
whenever multiple engineer working with same framework, their might be
possibilities one engineer modification, addition & deletion Might affect the
entire build.

 handle dependencies jars.

 Create framework configuration quick setup for new engineers (because all the
required dependencies jar. Versions declared in POM.xml, you just to get the
framework from the GIT & save the POM file.

 provide framework folder structure.

 we can run the test script in command Line without Eclipse

 Which is used to check framework build is broken or not ?

 Maven majorly support in Jenkins for CD/CI[Jenkins].

 Maven also support Profiling (we can have multiple testing.xml file in one
Project,

 so that we go for Profile to execute specific xml file via CMD).

 Maven also support Command Line parameters

Questions:

1. What is Maven explain Advantages.

2. Explain Maven Folder Structure.

3. Explain the dependencies feature in Maven.

4. Explain Build life Cycle.

5. What are the different maven commands.

6. What happens if we execute mvn test.


7. Write maven command to provide username and password through cmd line.

8. Write maven command to execute only one test class through cmd Line.

9. Write maven command to execute only one test method inside a test class
through cmd Line

10. How do you execute suite xml file through cmd line?

11. I have 5 different suite xml files for 5 different execution, i want to decide
which suite file to be executed during runtime, what is your approach.

12. how do you read data from cmd Line?

13. What are Maven parameters?

14. What is Maven Profiling?


GITHUB
Definition: It’s a distributed cloud decentralized repository where we can
maintain our source Code / Automation Framework / CRS doc /build of the
application in one place.

Software’s involved in GitHub


There are 2 Software in GitRepsitory
1. Git HUB: Cloud based repository(software), which is used maintain the source
code in one place, in order to use it just create an account with https://github.com
2. Git [Git client]: it’s a software should installed in client machine, which is used
to communicate to GITHUB.
E.g., EGit: Eclipse Git, Installed with Eclipse, we can execute git commands
through eclipse.
GitDeskTop/GitBash: Should be installed externally to execute git commands
through cmd line.
Advantages of GitHub Cloud
1. Since its cloud-based repository, no need to maintenance team to maintain the
Software / Hardware.
2. Cloud means pay rent for what you use
3. Cloud software always access via internet
4. Cloud System / sever physically not present within the Organization, but
present
virtually
5. Initial investment is not required for Software/ Physical location
6. Scale UP / Scale Down is easy
7. File Share between the team members is easier
8. It provides remote access, it means anywhere contributors can access via
internet
9. Provide History for changes made by users & backup facility
10. GitHub also provide platform to review [pull request] the Code of Automaton
test scripts
11. GitHub Also handle the conflict’s
12. Jenkins Always get the latest framework from the Git for batch Execution

Why Git is Decentralized Repository?


Git is Decentralized Repository because, in Git before pushing any Code to git Hub,
we have to commit the code to local repository first, make sure code is working in
Local Repository then push Code to GITHUB (Global Repo) There are Three stages
in Git, start with "Working Directory"->Local Repo->Global Repo

Usage of github at different stages:


1. Developers use github for: storage of source code
2. DevOps use github for: storage of build versions
3. Manual Testers use github for: storage of CRS and Manual test cases.
4. Automation Testers use github for: storage of Framework

Basic Git commands:


1. commit: commit will copy the framework from working directory to local
repository (. git folder created inside the project parent folder).
2. Push: push will copy the framework from local repository or. git folder to
GitHub global repository with URL and Username and Password/Token
3. Import+Clone URI: Import will get the framework from global repository to
the local systems clone URI will create a folder in the same name as the
framework URL in local system, which act as local repository for further push
actions.
4. Pull: Pull will help us to get the changes pushed into the framework. we can use
pull only if the project is existing in the working directory ie.. it should be already
imported. Only imported projects can be pulled.
5. Merge: Merge command will be merge one branch at a time with the master
6. Fork: Fork is a command which will create a copy of repository from different
github account into your github account.
7. Rebase: when their multiple branches existing to be merged, we can use rebase
to merge all the branches at a time with the master.
8. Pull Request: It’s an intimation given by the automation tester who creates a
branch to push the code to the manager/ team lead saying a new branch has been
created. Later the manager will look into the branch, analyse the code/changes
if there are no conflicts he will review and merge it into the master branchnof the
framework.
NOTE:
1. Project should be committed to local repo first and only then it can be pushed to
global repo. We cannot push without commit.
2. Project should be imported into working directory from global repo first only
then the changes made can be pulled. we cannot pull without import.
3. Project should be always pulled before pushing in order to avoid git conflicts.
4. Every test script should be pushed in a different branch and branch name
should be same as the test case ID. Once the test case is stable and all the review
comments are fixed, the branch should be merge with master and branch should
be deleted.

What is Git conflict?


 When two or more engineers try to make changes in the same repository
simultaneously, the first user trying to push the code will not face any issue,
but when the second user is trying to push the code, GitHub will throw
conflict. which means, GitHub thinks the second user is not aware of the
changes made by the first user hence it gives conflict and doesn’t allow
second user to push.
 When there is a conflict, GitHub will not accept the push, it will give
rejection msg.

How to resolve Git conflict?


1. Pull the code first before pushing.
2. Remove all unwanted comments.
3. Analyze the code pushed by others.
4. Then push it.

What is branching in GitHub?


Every time a new engineer joins the team, he will not be given collaborator right
into the master branch of the framework without which he cannot push the code
which he has written but he can pull the changes which others have written. So, in
order to push hascode, we prefer to push in separate branch and any senior tester
will review it and merge it into the master framework.

 Branching avoids unnecessary conflicts


 Branching avoids codes written by new engineers which might affect
the existing Framework.
 Branching makes sure that the master copy is safe from the
unreviewed changes.
 All the engineers will push their code in their branch and create a pull
request to the manager/ senior tester to review and merge it to
master.
 The code present in master is only available for pulling for all
automation tester.

What is pull Request?


 It’s an intimation given by the automation tester who creates a branch to
push the code into the branch to the manager/ team lead saying a new
branch has been created.
 Manager will get this intimation whenever any new branch has been created.
Later the manager will look into the branch, analyze the code/changes if
there are no conflicts he will review and merge it into the master branch of
the framework.

Questions:

1. Why GitHub?
2. What are different git commands
3. What is branching in GitHub
4. What is difference between git and GitHub?
5. What is pull request?
6. What is difference between merge and rebase?
7. can v pull without import?
8. can v push without commit?
9. Explain GitHub architecture
JENKINS
Jenkins is a CI/CD Tool used by Developers, DevOps and Automation Testers.

CI: Continuous Integration

CD: Continuous Development, Continuous Deployment, Continuous Delivery

Basically, Jenkins automates

 Process of build creation: Continuous development.


 Process of installing the build into testing environment: Continuous
deployment.
 Process of checking the integration issues between old feature and new
features: continuous integration.
 Process of delivering the tested the build to the production environment:
Continuous delivery.

Why Jenkins is required in development?

Continuous development: continuous monitor the git source code repository &
create a new build if any changes happened in the git source code.

Continuous deployment: get the latest build from git location & deploy the build
in to testing environment.

Continuous Delivery: get the latest build from git location & deploy the build in to

UAT environment/Production environment.

Why Jenkins is required in Automation?

Continuous Integration: Continuous execution of the selenium test scripts in


testing environment to check the integration issues.

Automation Engineers used Jenkins for Continuous Integration.

Continuous Integration means checking the integration issues between the old
build and the new feature by executing the old framework. if the test scripts get
failed, then with the failure we will get to know the impact of new feature on the
old build. Hence, we can analyze the failure, debug the failed test scripts, if any
product issues/bugs are found we will rise the defect in Jira, if it’s a test script
issue we will correct it update the framework and re run the framework.
Jenkins Configuration

 Login to Jenkins
 Dashboard -> Manage Jenkins -> Global Tool Configuration
 Set path for jdk, git, Maven.

Create Job in Jenkins:

 Login to Jenkins
 New Item -> Name of the job -> Choose Maven Project
 Provide the git location where the project is stored
 Provide schedule to trigger the execution of the job
 Root Pom -> specify the pom.xml location inside the project
 Goal -> default goal for tester is test.

All maven commands can be given like:

 test -P SmokeSuite
 -Dbrowser=Chrome -Dusername=Chaitra test
 Provide any post build actions if needed.
 Save the job.

Parameters in Jenkins:

 Jenkins also supports parameters but internally its maven parameter


only
 We use $ for specifying Jenkins parameter
 Choice parameters provide multiple choices for data that can be
chosen during the execution.
 Using Jenkins parameter in goal
 -Dbrowser=$browser -Dusername=Chaitra -Durl=$url test
 Here browser and URL can be chosen during build now action.

Why Jenkins parameters required?

Sometimes customer might want to execute the job with different browser or in
different environment, since customer cannot make changes in framework, we
provide choice parameters so that it gives a drop down of different choices given
like different browser names, different environment, customer can easily choose
from drop down and execute the job. No coding knowledge needed to run the job.
scheduling Job in Jenkins:

Scheduling decides when the job execution should be triggered or started.

There are 3 types of Scheduling in Jenkins:

 On Demand
 On schedule
 Poll SCM

1. On Demand scheduling:

 Whenever the customer demands the execution, we will trigger the


execution with Build Now option available.
 There are no stipulated times for execution, whenever customer demands,
we can run.
 Build Now is the action performed for on demand scheduling.

2. On Schedule scheduling:

 Specifying the exact time duration of when the execution should start is
called on schedule scheduling.
 While configuring the job only we have to provide "build periodically" in
Build Triggers.
 Jenkins follow a specific scheduling format.

MINUTE HOUR DOM MONTH DOW

(0-59) (0-23) (1-31) (1-12) (0-7)-> 0,7=Sunday

# Every Tuesday at 12pm

H 12 * * * -> Here "H" means hash -> specifies "any", "*" specifies
"every"

# Every fifteen minutes (perhaps at :07, :22, :37, :52):

H/15 * * * *

# Every ten minutes in the first half of every hour

H (0-29)/10 * * * *

# Once every two hours at 45 minutes past the hour starting

45 9-16/2 * * 1-5

# Once in every two-hour slot between 8 AM and 4 PM every weekday


H H (8-15)/2 * * 1-5

# Once a day on the 1st and 15th of every month except December

H H 1,15 1-11 *

 On Schedule does not bother if the framework is updated or not, it will start
the execution immediately in the specified time schedule.

3. Poll SCM:
 Poll SCM will detect the changes made in specified git location (SCM- Source
Code management) and it will start the execution on the scheduled time.
 Here the schedule will be usually H * * * *
 Whenever any changes are detected like new push /commit it will trigger
the job.
 When we make any changes in the framework, it has to pushed into git
master repo or if it’s pushed into any branches then it has to be reviewed
and merged into the master.
 Usually, Master repo of the framework will be configured with Jenkins and
if any new commit is recognized, Jenkins will start the execution based on
schedule.

Pipelining in Jenkins:

 Pipelining means creating dependency between multiple jobs.


 If one job is triggered it will be executed and the status of this job will
automatically trigger the next job.
 Usually, the previous job is called Upstream job and the next job is called
downstream job.
 Build creation (Job 1)->Smokesuite(job 2)->RegressionSuite(job 3) these
are the 3 jobs.

which will be in pipeline

Even though we create pipelining for jobs during job configuration, we have to
check the individual jobs to make sure whether they are executing or not as there
is no view to showcase all the jobs running in pipeline. Hence, we use "Build
Pipeline Plugin" to see pipeline view, where all the jobs which are in pipeline are
visible at once.

Advantages of Jenkins:

a. Jenkins Provide 3 level of execution

- On demand: based on Customer demand we can start the execution.


- On Scheduling: based on scheduled time, start the execution automatically.

- POOL SCM: where continuously monitor the SCM(GitHub) & automatically


start the execution whenever we get new Build / one new test script is getting
added to Git.

b. Email Notification:

- Jenkins sends out an execution Report via email, once execution is completed

- Jenkins also Send Build broken Email, when Compilation issue between the

framework component.

c. Jenkins also support run time parameter.

d. Jenkins also support Pipelines Job.

Questions:

1. How do you create a job in Jenkins.

2. Schedule a job in Jenkins to run every Thursday.

3. Schedule a job in Jenkins to run every 4th day of the month at 2pm.

4. What are Jenkins parameters?

5. Even we want pass run time data in Jenkins, what is your approach.

6. What are different scheduling in Jenkins.

7. What are the advantages of Jenkins.

8. What is Poll SCM.

9. Why Jenkins pipeline is required.

10. What is the default goal in Jenkins.

11. What is the relationship between TestNg-maven-Git-Jenkins


AWS - Amazon Web services
What is Cloud Computing?
Rather than managing files on a local storage device, cloud computing makes it
possible to save then over the internet.
Advantages of cloud-based systems:
1. No physical systems needed
2. No admins needed
3. No infrastructure needed
4. Cloud systems will provide high data recovery
5. Cloud systems provide high security
6. Cloud systems provide Data backup
7. Cost effective
8. Pay for what you Use model
9. Scale up and scale down cost is less
Cloud computing serves 2 model
1. Deployment model
2. Service model
1. Deployment Model:
 The cloud deployment model identifies the specific type of cloud
environment based on ownership, scale, and access, as well as the cloud’s
nature and purpose.
 The location of the servers you’re utilizing and who controls them are
defined by a cloud deployment model.

Types of Deployment Model:


a. Public Cloud:
 The public cloud makes it possible for anybody to access systems and
services.
 The public cloud may be less secure as it is open for everyone.
b. Private Cloud:
 The private cloud deployment model is the exact opposite of the public
cloud deployment model. It’s a one-on-one environment for a single user
(customer).
 There is no need to share your hardware with anyone else. The
distinction between private and public cloud is in how you handle all of
the hardware.
 It is also called the “internal cloud” & it refers to the ability to access
systems and services within a given border or organization.

c. Hybrid Cloud:
 It’s a combination of public cloud and private cloud.
 examples: Federal agencies
2. Services model:
Defines the type of services which are provided by cloud vendors to the customers.
Types of service Models
a. IAAS (Infrastructure as a Service):
 It is a computing infrastructure managed over the internet. The main
advantage of using IaaS is that it helps users to avoid the cost and
complexity of purchasing and managing the physical servers.
 Examples: Digital Ocean, Linode, Amazon Web Services (AWS), Microsoft
Azure.
 Used By: IT Admins.

b. PAAS (Platform as a Service):


 PaaS cloud computing platform is created for the programmer to develop,
test, run, and manage the applications.
 Examples: AWS Elastic Beanstalk, Windows Azure, Heroku, Force.com,
Google App Engine.
 Used By: Software Developers.

c. SAAS (Software as a Service):


 SaaS is also known as "on-demand software". It is a software in which the
applications are hosted by a cloud service provider. Users can access these
applications with the help of internet connection and web browser.
 Examples: BigCommerce, Google Apps, Salesforce, Dropbox, ZenDesk, Cisco
WebEx
 Used By: End Customers.

SELENIUM GRID:
 Selenium grid is a collection of libraries from Selenium RC + Selenium
Webdriver +Selenium Grid Server.
 Selenium Grid: It’s an open source available in Selenium community and it
acts like a server for remote execution and Compatibility testing.
 Selenium grid is used to perform

• Remote Execution

• Cross Browser testing

• Cross Platform Testing

1. REMOTE EXECUTION: executing the test script in any remote devices like
cloud machines, other computers in the same network, mobile devices like android
or IOS with the help of selenium grid is called as Remote Execution.

To run Selenium grid:


1. Download the Selenium standalone Server.jar from Selenium downloads.
2. Use the below command to run the Server manually
cmd>java -jar <path of sss.jar>
2. CROSS Browser Execution: Executing the test script in Multiple browsers and
performing compatibility testing is called as Cross browser execution Selenium
grid enables to perform cross browser execution with multiple browsers
configured in multiple VMs.
1. CROSS Platform Execution:
 Executing the test script in Multiple platforms and performing compatibility
testing is called as Cross platform execution Selenium grid enables to perform
Cross platform execution with multiple platforms like MacOS, Windows,
Mobile, Linus configured in multiple VMs.
 To perform Cross Browser and Cross Platform Execution , we have to make use
of Hub and Node Concept of Selenium Grid as we have use multiple threads to
trigger the execution.
HUB and NODE in Selenium GRID:
 In selenium grid, concept of hub and node helps to configure more than one
node for a hub.
 HUB acts as the master which will receive the command from selenium and
bypass that to nodes.
 Default port number is 4444, if its busy, port number can be changed like
below.
TO run Selenium HUB:
 cmd>java -jar <path of sss.jar> -role hub -port 4444
To run Selenium Node and configure Chrome Driver - Chrome browser
 cmd>java -Dwebdriver.chrome.driver=<path of chrome driver executable file>
-jar <path of sss.jar>
 role node -hub <path of hub configured> -port 5555
To run Selenium Node and configure Gecko Driver - Firefox Browser
 cmd>java -Dwebdriver.chrome.driver=<path of gecko driver executable file> -
jar <path of sss.jar>
 role node -hub <path of hub configured> -port 6666
To check the Selenium Grid console:
 Go to browser and hit the below URL : http://localhost:4444/grid/console

You might also like