You are on page 1of 80

Agenda

Day Topic Artifact & Expectation


1  What is an Automation Testing .
 DOM searching & manipulation using Chrome Browser the trainee will be able to understand the
Automation Testing & searching over DOM of
Browser
2 Complete 8 xPath searching of sample page
 Xpath searching using Chrome Browser Eclipse Project of Selenium with Maven
 Configuration of Eclipse IDE Selenium Project with
Maven The trainee will be able to create a Selenium
 How to Uses WebDriver, WebElement and Locators Project with Eclipse IDE and configure the
WebDrive connector

3  How to Handle Windows & Alert Create a java class to handle Alert , Pop up
 How to Handle a Select Element and List of Windows & WebElement(s)
WebElements The trainee will be able to handle Alert ,
Window & WebElement(s) using Selenium
4  Implicit Wait and Explicit Wait The trainee will be able to understand Wait
 Hard Assert & Soft Assert with Junit concept in Selenium and Assert.
 Suite JUnit Also how to run the Test cases using Junit
Framework

1
Agenda
Day Topic Artifact & Expectation
5,6
 Exercise 1 , Automate 3 Test Cases Generate the code for Automation of 3 Test

7,8
Redo the Project using the Design Pattern POM
The trainee will be able to generate an
 Refactoring Project with Page Object Model
automation.
Testing project using POM.

9 Add the concept of Data Driven using


 Installing Gherkin & Cucumber in the Eclipse Gherkin language
IDE The trainee will be able to configure cucumber
framework
10 Redo the Project using the Gherkin
 Refactoring Project with Gherkin The trainee will be able to understand the
gherkin framework and generate test cases
with Gherkin language

2
Day 1
Prerequisites

Prerequisites for the participant

Previous knowledge
 Java SE (1 year of experience)
 HTTP , DOM , Javascript (1 year of experience)

A computer in TCS with



JDK 1.8 ,

Eclipse IDE

Library 101 (jar libraries that will need to run in the examples and the project)

http://demo.guru99.com access


Access to download gherkin-cucumber plugin https://marketplace.eclipse.org/content/cucumber-eclipse-plugin

Access to download chromedriver.exe https://chromedriver.chromium.org/downloads

3
Day 1
What is Software Testing?


Software testing is defined as an activity to check whether the actual results match the expected
results and to ensure that the software system is Defect free.


It involves execution of a software component to evaluate one or more properties of interest.


It can be either done manually or using automated tools.

 In simple terms, Software Testing means Verification of Application Under Test

4
Day 1
Scope & Traceability in SDLC

5
Day 1
Major Phases Software Development Life Cycle

6
Day 1
Types Of Software Testing

Functional Testing types include:


Unit Testing

Integration Testing

System Testing
 Smoke Testing
 Regression Testing
 Beta/Acceptance Testing

Non-functional Testing types include:

 Performance Testing

Load Testing

Volume Testing

Security Testing

Install Testing

Localization Testing

7
Day 1

What is a testing environment?


A testing environment is a setup of software and hardware for the testing teams to execute
test cases. In other words, it supports test execution with hardware, software and network
configured. Test bed or test environment is configured as per the need of the Application Under
Test.

8
Day 1

What are the different environments in software development?


The main SDLC environments include:


The Analysis and Design Environment
 The Development Environment
 The Common Build Environment
 The Testing Environment:
• This has two components:
• The Systems Integration Testing Environment
• The User Acceptance Testing Environment
 The Production Environment.

9
Day 1
Mapping environments vs SDLC?

1?

2?

3?

10
Day 1
What is Automation Software Testing ?
Manual Testing is performed by a human sitting in front of a computer carefully executing the test steps.

Automation Testing means using an automation tool to execute your test case suite.

The automation software can also enter test data into the System Under Test, compare expected and actual
results and generate detailed test reports. Test Automation demands considerable investments of money
and resources.

Successive development cycles will require execution of same test suite repeatedly. Using a test automation
tool, it's possible to automate this test suite and re-play it as required. Once the test suite is automated, no
human intervention or less human intervention is required. This improved ROI of Test Automation.

The goal of Automation is to reduce the number of test cases to be run manually and not to eliminate
Manual Testing altogether.

11
Day 1
Automation Framework Architecture
Development View
Development Testing Infrastructure Under Test App

App 1
Browser1
Web Front End
Eclipse IDE
Automation Framework Publi
c
Back
Test NG & Report NG End

Maven & Selenium & Spring Core & JPA pull/push version
& assets D
B
JDK 1.8

GIT
Master Dev

ESB/EDI
DB Repo
VMware

Browser1

Automation
Framework
Jenkins build & deploy & execute
CI TestNG

12
Day 1
Questions
 List the test environments used
in an SDLC Test
Environmen
 What are the SDLC Major Phases? t

 What are the Testing Types?

 How do I know the scope


 of a release ?
Scope
 What does a
 test automation do? Testing
Phase Type

13
Day 1
What is Selenium?

Selenium is a free (open source) automated testing suite for web applications
across different browsers and platforms. It is quite similar to HP Quick Test
Pro (QTP now UFT) only that Selenium focuses on automating web-based
applications. Testing done using Selenium tool is usually referred as
Selenium Testing.

Selenium automates the web application by accessing the browser's DOM

14
Day 1
Who developed Selenium?

Since Selenium is a collection of different tools, it had different developers as well.

Primarily, Selenium was created by Jason Huggins in 2004. An engineer at


ThoughtWorks, he was working on a web application that required frequent testing.
Having realized that the repetitious Manual Testing of their application was becoming
more and more inefficient, he created a JavaScript program that would automatically
control the browser's actions. He named this program as the "JavaScriptTestRunner."

Seeing potential in this idea to help automate other web applications, he made
JavaScriptRunner open-source which was later re-named as Selenium Core.

15
Day 1
Selenium Suite

16
Day 1
Selenium Web Driver Architecture
HTTP over HTTP

Selenium Language
Bindings Web Drivers Web Browsers

FireFox
FireFoxDriver Browser
Java

Safari
SafariDriver Browser
Ruby
Json Wire
Protocol Chrome
ChromeDriver
c# Browser
http://localhost:8080/
{"url":"https://www.softwaretesting Edge
EdgeDriver
Python material.com"} Browser
Opera
Javasc OperaDriver
ript
Browser

HTTP over HTTP


17
Day 1
Birth of Selenium RC

So another ThoughtWork's engineer, Paul Hammant, decided to create a server that will act
as an HTTP proxy to "trick" the browser into believing that Selenium Core and the web
application being tested come from the same domain. This system became known as the
Selenium Remote Control or Selenium 1.

18
Day 1
Birth of WebDriver
Simon Stewart created WebDriver circa 2006 when browsers and web applications were
becoming more powerful and more restrictive with JavaScript programs like Selenium Core. It
was the first cross-platform testing framework that could control the browser from the OS level.

19
Day 1
WebDriver vs Selenium RC

Selenium RC exists before Selenium WebDriver back in 2006.


Both have the common features given as follows.

 Test scripts can be written in different programming languages.


 Tests can be executed across different web browsers.

Now the question should be, what is the actual difference?

20
Day 1
WebDriver vs Selenium RC

If your browser and tests will all run on different machines


then you will need to run the Selenium-Server.

21
Day 1
Birth of Selenium Grid

Selenium Grid was developed by Patrick Lightbody to address the need of minimizing test
execution times as much as possible. He initially called the system "Hosted QA." It was
capable of capturing browser screenshots during significant stages, and also of sending out
Selenium commands to different machines simultaneously.

https://www.guru99.com/introduction-to-selenium-
grid.html
22
Day 1
Summary

The entire Selenium Tool Suite is comprised of four components:

Selenium IDE, a Firefox add-on that you can only use in creating relatively simple test cases and
test suites.
Selenium Remote Control, also known as Selenium 1, which is the first Selenium tool that allowed
users to use programming languages in creating complex tests.
WebDriver, the newer breakthrough that allows your test scripts to communicate directly to the
browser, thereby controlling it from the OS level.
Selenium Grid is also a tool that is used with Selenium RC to execute parallel tests across
different browsers and operating systems.
Selenium RC and WebDriver was merged to form Selenium 2.

23
Day 1
Automation Framework Architecture
Development View
Development Testing Infrastructure Under Test App

App 1
Browser1
Web UI
Eclipse IDE
Gherkin Cucumber Publi
c
Back
JUnit End

Selenium (POM) pull/push version


& assets D
B
JDK 1.8

GIT
Master Dev

ESB/EDI
DB Repo
VMware

Browser1

Gherkin
Jenkins build & deploy & execute
CI Junit

24
Day 1
What is the HTML DOM?
The HTML DOM is a
standard object model
and programming interface for HTML.

It defines:
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML
elements

The events for all HTML elements


In other words: The HTML DOM is a
standard for how to get, change, add,
or delete HTML elements.
https://www.w3schools.com/js/js_htmldom.asp

25
Day 1
Example HTML DOC
Example
<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "
Hello World!";
</script>

</body>
The getElementById Method
</html>
The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.

The innerHTML Property


The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML
elements.
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>

26
Day 1
Exercise
Go to http://demo.guru99.com/v1/
Type in console :
document.getElementById('message23').innerHTML = 'Hola';

27
Day 1
Finding HTML Elements

Method Description
document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Type in console :
>document.getElementsByTagName('label')[1].innerHTML = 'BBB';
>document.getElementsByTagName('label')[0].innerHTML = 'AAA';
>document.getElementsByName('uid')[0].value = '123';
> Modify password input value (write down the script line)

28
Day 1
Changing HTML Elements
Property Description
element.innerHTML =  new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML element

element.style.property = new style Change the style of an HTML element

Method Description

element.setAttribute(attribute, value) Change the attribute value of an HTML element

Sample Deactivate an input :


document.getElementsByName('password')[0].disabled = 'true';

Modify an attribute value:


document.getElementsByName('password')[0].type = 'text';
document.getElementsByName('password')
[0].setAttribute('type','password');
document.getElementsByName('password')[0].style.display = 'none';
29
Day 1
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element


document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

Sample :

> var current11 = document.getElementsByName('frmLogin')[0];


> var newDiv = document.createElement("div");
> var newContent = document.createTextNode("Hi there and greetings!");
> newDiv.appendChild(newContent);
> current11.appendChild(newDiv);
> newDiv.id = "lst1";
> document.getElementById('lst1').innerHTML = 'Changeit!';

30
Day 1

Questions
1) What is an attribute in the DOM ?

2) List at least 3 elements (tag) from the DOM

3) How Can I modify an element dynamically in the DOM ?

4) Which is the protocol of a webDriver implementation (chromedriver.exe) to


communicate with the binding language (java , c#) ?

5) Do I can run a test on a browser that is on a remote machine using


ChromeWebDriver ?

31
Day 2
Xpath

XML path.
It is a language for
finding any element on
the web page using XML
path expression.

https://www.guru99.com/xpath-selenium.html

32
Day 2
Xpath

Standard syntax for creating XPath is.

Xpath=//tagname[@attribute='value']

// : Search over all DOM Tree.

Tagname: Tagname of the particular element or node.

@: Select attribute.
Attribute: Attribute name of the element.

Value: Value of the attribute.

33
Day 2
Searching Type

Absolute XPath:
It is the direct way to find the element, but the disadvantage of
the absolute XPath is that if there are any changes made in the
path of the element then that XPath gets failed.
The key characteristic of XPath is that it begins with the single
forward slash(/) ,which means you can select the element from
the root node.
Below is the example of an absolute xpath expression of the
element shown in the below screen.
Absolute xpath:
html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4[
1]/b

34
Day 2
Searching Type

Relative Xpath

For Relative Xpath the path starts from the middle of the HTML DOM
structure. It starts with the double forward slash (//), which means it can
search the element anywhere at the webpage.

You can start from the middle of the HTML DOM structure and no need
to write long xpath.

Below is the example of a relative XPath expression of the same


element shown in the below screen. This is the common format used to
find element through a relative Xpath.

Relative xpath: //*[@class='featured-box']//*[text()='Testing']

35
Day 2
Exercise using Chrome console

Go to http://demo.guru99.com/v1/
Type $x() in the inspector console section with Chrome
Xpath= $x(“//input[@type='text']”)
Xpath= //label[@id='message23']
Xpath= //input[@value='RESET']
Questions
What is the searching to find all elements with class = barone ?

What is the searching to find an element anchor with href


=http://demo.guru99.com/ ?

36
Day 2
References Xpath

Go to https://devhints.io/xpath
Page to practice
http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm
Most common functions are :
contains() // font[contains(@class,"head")]
starts-with() // font[starts-with(@class,"head")]
ends-with() // font[ends-with(@class,"head")]
name() //[starts-with(name(), 'h')]
text() //button[text()="Submit"]
37
Day 2
Configure Eclipse IDE

Download the Chromedriver.exe , and copy in a local path c:/users/abc/

Be sure that Your Eclipse is updated and JDK 1.8 is installed

Create a java project without maven

 Create a java project , add 2 source paths /src/main/java and /src/test/java

 Add the jars in BuildPath (library101)

Create a java project with Maven

(https://www.techbeamers.com/running-webdriver-tests-using-maven-eclipse/)

 Create a maven project with Arche-type-quicktstart

 Add a groupId and artifactId

 Add dependecies in the pom.xml , modify the setting.xml in .m2 repo

38
Day 2
Execute the WebDriver using
ChromeDriver
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.junit.Test;

public class GettingStarted {


@Test
public void testGoogleSearch() throws InterruptedException {

System.setProperty("webdriver.chrome.driver",
"C:\\Users\\559482\\Desktop\\1818811\\chromedriver.exe");

WebDriver driver = new ChromeDriver();


driver.get("http://www.google.com/");
Thread.sleep(5000); // Let the user actually see something!
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("tcs");
searchBox.submit();
Thread.sleep(5000); // Let the user actually see something!
driver.quit();
}
}
39
Day 2
Type Locators

40
Day 2
Locator Sample
public class ClassNameLocator {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "C:\\Users\\559482\\chromedriver.exe");

WebDriver driver=new ChromeDriver();


driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

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

// System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
//Opening the air bnb home page
driver.get("https://www.uber.com/mx/es");

driver.findElement(By.xpath("//a[@id='1']")).click();
driver.findElement(By.xpath("//input[@name='pickup']")).sendKeys("Tata 3" + Keys.ENTER);
driver.findElement(By.xpath("//a[@data-baseweb='button' and @aria-label='Pedir
ahora']")).click() ;
driver.close();
//closing the driver
driver.quit();
}}

41
Day 2

Questions
1) How can I Check an Xpath search expression (Tools and how )?

2) What is the difference between an absolute search and relative search in Xpath ?

3) How can I join more than 1 search condition in a Xpath Expression (section inside of the [])?

4) How can I declare the chromedriver.exe path in java ?

5) List at least 3 type of Locators

6) What is the Class to create a Locator in Selenium ?

42
Day 2

Questions
1) How can I Check an Xpath search expression (Tools and how )?

2) What is the difference between an absolute search and relative search in Xpath ?

3) How can I join more than 1 search condition in a Xpath Expression (section inside of the [])?

4) How can I declare the chromedriver.exe path in java ?

5) List at least 3 type of Locators

6) What is the Class to create a Locator in Selenium ?

43
Day 3
Alert & Pop Windows Handling
https://www.guru99.com/alert-popup-handling-selenium.html

import org.openqa.selenium*;
public class AlertDemo {

public static void main(String[] args) throws NoAlertPresentException,InterruptedException {

System.setProperty("webdriver.chrome.driver",
"C:\\Users\\559482\\Desktop\\1818811\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// Alert Message handling
driver.get("http://demo.guru99.com/test/delete_customer.php");
driver.findElement(By.name("cusid")).sendKeys("53920");
driver.findElement(By.name("submit")).submit();

// Switching to Alert
Alert alert = driver.switchTo().alert();

// Capturing alert message.


String alertMessage= driver.switchTo().alert().getText();
// Accepting alert
alert.accept();}}
44
Day 3
Alert & Pop Windows Handling
WebDriver driver=new ChromeDriver();
//Launching the site.
driver.get("http://demo.guru99.com/popup.php");
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click();

String MainWindow=driver.getWindowHandle();
// To handle all new opened window.
Set<String> s1=driver.getWindowHandles();
Iterator<String> i1=s1.iterator();
while(i1.hasNext())
{
String ChildWindow=i1.next();
if(!MainWindow.equalsIgnoreCase(ChildWindow))
{
// Switching to Child window
driver.switchTo().window(ChildWindow);
driver.findElement(By.name("emailid")).sendKeys("gaurav.3n@gmail.com");
driver.findElement(By.name("btnLogin")).click();
// Closing the Child Window.
driver.close();
}
}
// Switching to Parent window i.e Main Window.
driver.switchTo().window(MainWindow);
45
Day 3
WebElement & WebElements
https://www.guru99.com/find-element-selenium.html

WebElement
Selenium Webdriver represents all the HTML elements as
WebElements. This class provides a mechanism to represent
them as objects & perform various actions on the related
elements. Typically, the findElement method in WebDriver
returns an object of class webElement.

WebElements
FindElements() it returns you WebElements i.e
List<WebElement> of multiple elements. It return 1 if only one
element present in it or multiple if presents more.
List<WebElement> listOfElements =driver.findElements(By.xpath("//div"));

46
Day 3
WebElement & WebElements
Example of WebElement

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver",
"C:\\Users\\559482\\Desktop\\1818811\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("http://demo.guru99.com/test/ajax.html");

// Find the radio button for “No” using its ID and click on it
driver.findElement(By.id("no")).click();

//Click on Check Button


driver.findElement(By.id("buttoncheck")).click();
}

47
Day 3
WebElement & WebElements
Example of WebElements

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver",
"C:\\Users\\559482\\Desktop\\1818811\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("http://demo.guru99.com/test/ajax.html");

List<WebElement> elements = driver.findElements(By.name("name"));


System.out.println("Number of elements:" +elements.size());

for (int i=0; i<elements.size();i++){


System.out.println("Radio button text:" + elements.get(i).getAttribute("value"));
}
}
48
Day 3
Handling a DropBox with Selenium
https://www.guru99.com/select-option-dropdown-selenium-webdriver.html

Methods
 selectByVisibleText() and deselectByVisibleText()
 selectByValue() and deselectByValue()
 selectByIndex() and deselectByIndex()
 IsMultiple()
 DeselectAll()

Select drpCountry = new Select(driver.findElement(By.name("country")));


drpCountry.selectByVisibleText("ANTARCTICA");

//Selecting Items in a Multiple SELECT elements


driver.get("http://jsbin.com/osebed/2");
Select fruits = new Select(driver.findElement(By.id("fruits")));
fruits.selectByVisibleText("Banana");
fruits.selectByIndex(1);

49
Day 3

Questions
1) How can I access a popup Windows or another tab window using Selenium ?

2) How can I close a Alert Message using Selenium ?

3) How to get a List of WebElement in Selenium(Which Class and method)?

4) How to get a references of a DropBox element in Selenium ?

5) How to get a references of a Input element in Selenium ?

6) How to type a value over an Input element in Selenium ?

7) How to click on a button element in Selenium ?

50
Day 3

Questions
1) How can I access a popup Windows or another tab window using Selenium ?

2) How can I close a Alert Message using Selenium ?

3) How to get a List of WebElement in Selenium(Which Class and method)?

4) How to get a references of a DropBox element in Selenium ?

5) How to get a references of a Input element in Selenium ?

6) How to type a value over an Input element in Selenium ?

7) How to click on a button element in Selenium ?

51
Day 4
Implicit and Explicit Wait
https://www.guru99.com/implicit-explicit-waits-selenium.html

Implicit Wait
The implicit wait will tell to the web driver to wait for certain amount of time
before it throws a "No Such Element Exception". The default setting is 0. Once
we set the time, web driver will wait for that time before throwing an exception.

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;

52
Day 4
Implicit and Explicit Wait
https://www.guru99.com/implicit-explicit-waits-selenium.html

Explicit Wait
The explicit wait is used to tell the Web Driver to wait for certain conditions
(Expected Conditions) or the maximum time exceeded before throwing an
"ElementNotVisibleException" exception.

The explicit wait is an intelligent kind of wait, but it can be applied only for
specified elements. Explicit wait gives better options than that of an implicit wait
as it will wait for dynamically loaded Ajax elements.

Once we declare explicit wait we have to use "ExpectedCondtions" or we can


configure how frequently we want to check the condition using Fluent Wait.
These days while implementing we are using Thread.Sleep() generally it
is not recommended to use

53
Day 4
Implicit and Explicit Wait
https://www.guru99.com/implicit-explicit-waits-selenium.html

Example of Explicit Wait


WebDriver driver = new ChromeDriver();
WebDriverWait wait=new WebDriverWait(driver, 20);
String eTitle = "Demo Guru99 Page";
String aTitle = "" ;
// launch Chrome and redirect it to the Base URL
driver.get("http://demo.guru99.com/payment-gateway/check_credit_balance.php" );
driver.findElement(By.xpath("//input[@id='card_nmuber']")).sendKeys("11");
boolean label1;
System.out.println( "Before Wait Element" );
label1= wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("message1"),
"Please Input Correct 16 Digit." ));
System.out.println( "After Wait Element and result was " + label1);
driver.findElement(By.name("submit")).click();
System.out.println( "After click" );

Alert alertA = wait.until(ExpectedConditions.alertIsPresent());


String str1 = alertA.getText();
assertEquals("Check card number is 16 digits!", str1);
alertA.dismiss();
54
Day 4
Implicit and Explicit Wait
https://www.guru99.com/implicit-explicit-waits-selenium.html

Method of ExpectedConditions Class


alertIsPresent()
elementSelectionStateToBe()
elementToBeClickable()
elementToBeSelected()
frameToBeAvaliableAndSwitchToIt()
invisibilityOfTheElementLocated()
invisibilityOfElementWithText()
presenceOfAllElementsLocatedBy()
presenceOfElementLocated()
textToBePresentInElement()
textToBePresentInElementLocated()
textToBePresentInElementValue()
titleIs()
titleContains()
visibilityOf()
visibilityOfAllElements()
visibilityOfAllElementsLocatedBy()
visibilityOfElementLocated()
55
Day 4
Junit Framework
https://www.guru99.com/junit-tutorial.html

JUnit is an open source Unit Testing Framework for JAVA. It is useful for Java
Developers to write and run repeatable tests. Erich Gamma and Kent Beck
initially develop it. It is an instance of xUnit architecture. As the name implies, it
is used for Unit Testing of a small chunk of code

Clases to run Test ,


 org.junit.TestCase
 org.junit.TestResult
 org.junit.TestSuite
Annotations, (It is a way to organize the sequence of start up operations and
tear down operations between the execution of tests cases)
Assert , It is a way to verify the expected results of a Test Case.

56
Day 4
Junit @Annotation

 @Before
 @After
 @Test
 @BeforeClass
 @AfterClass
 @Ignore
 @RunWith

57
Day 4
Junit @Annotation
Annotations Description

1. @Test This annotation is a replacement of org.junit.TestCase which


indicates that public void method to which it is attached can
be executed as a test Case.
2. @Before This annotation is used if you want to execute some
statement such as preconditions before each test case.

3. @BeforeClass This annotation is used if you want to execute some


statements before all the test cases for e.g. test connection
must be executed before all the test cases.
4. @After This annotation can be used if you want to execute some
statements after each  Test Case  for e.g resetting variables,
deleting temporary files ,variables, etc.

58
Day 4
Junit @Annotation
Annotations Description

5. @AfterClass This annotation can be used if you want to execute some


statements after all test cases for e.g. Releasing resources
after executing all test cases.
6. @Ignores This annotation can be used if you want to ignore some
statements during test execution for e.g. disabling some test
cases during test execution.
7. @Test(timeout=500) This annotation can be used if you want to set some timeout
during test execution for e.g. if you are working under some
SLA (Service level agreement), and tests need to be
completed within some specified time.
8. @Test(expected=IllegalArgumentEx This annotation can be used if you want to handle some
ception.class) exception during test execution. For, e.g., if you want to
check whether a particular method is throwing specified
exception or not.

59
Day 4
Junit Assert
https://junit.org/junit4/javadoc/4.8/org/junit/Assert.html
https://www.guru99.com/junit-assert.html

What is Junit Assert?

Assert is a method useful in determining Pass or Fail status of a test case, The
assert methods are provided by the class org.junit.Assert which extends
java.lang.Object class.

There are various types of assertions like Boolean, Null, Identical etc.

Junit provides a class named Assert, which provides a bunch of assertion


methods useful in writing test cases and to detect test failure

60
Day 4
Junit Assert
Method Description
1. void assertEquals(boolean expected, It checks whether two values are equals similar to equals
boolean actual) method of Object class
2. void assertFalse(boolean condition) functionality is to check that a condition is false.

3. void assertNotNull(Object object) "assertNotNull" functionality is to check that an object is not


null.
4. void assertNull(Object object) "assertNull" functionality is to check that an object is null.

5. void assertTrue(boolean condition) "assertTrue" functionality is to check that a condition is true.

6. void fail() If you want to throw any assertion error, you have fail() that
always results in a fail verdict.
7. void assertSame([String message] "assertSame" functionality is to check that the two objects
refer to the same object.
8. void assertNotSame([String "assertNotSame" functionality is to check that the two objects
message] do not refer to the same object.

61
Day 4
Junit Framework
https://www.guru99.com/junit-assert.html
Example of Assert
String string1="Junit";
String string2="Junit";
String string3="test";
String string4="test";
String string5=null;
int variable1=1;
intvariable2=2;
int[] airethematicArrary1 = { 1, 2, 3 };
int[] airethematicArrary2 = { 1, 2, 3 };
//Assert statements
assertEquals(string1,string2);
assertSame(string3, string4);
assertNotSame(string1, string3);
assertNotNull(string1);
assertNull(string5);
assertTrue(variable1<variable2);
assertArrayEquals(airethematicArrary1, airethematicArrary2);
62
Day 4
Junit Framework
Reference of all Junit Assert
https://www.journaldev.com/21681/junit-assertions

1 JUnit Assertions
1.1 fail()
1.2 assertNull() and assertNotNull()
1.3 assertSame() and assertNotSame()
1.4 assertTrue() and assertFalse()
1.5 assertEquals() and assertNotEquals()
1.6 assertArrayEquals()
1.7 assertIterableEquals()
1.8 assertThrows()
1.9 assertDoesNotThrow()
1.10 assertAll()
1.11 assertTimeout()
1.12 assertTimeoutPreemptively()

63
Day 4
Junit Test Suite
https://www.guru99.com/create-junit-test-suite.html

Create JUnit Test Suite with Example: @RunWith @SuiteClasses


In Junit, test suite allows us to aggregate all test cases from multiple
classes in one place and run it together.

To run the suite test, you need to annotate a class using below-
mentioned annotations:

@Runwith(Suite.class)
@SuiteClasses(test1.class,test2.class……) or
@Suite.SuiteClasses ({test1.class, test2.class……})

With above annotations, all the test classes in the suite will start
executing one by one.

64
Day 4
Junit Advanced Features

 Error Collector https://www.guru99.com/junit-errorcollector.html


 Parameterized Junit Test https://www.guru99.com/junit-parameterized-test.html

65
Day 4

Questions
1) What is the difference between an Implicit Wait and an Explicit Wait ?

2) What is the purpose to uses a Explicit Wait ?

3) List at Least 3 Selenium Exceptions

4) List a method of ExpectedCondition Class

5) What is the @test annotation in jnit Class for ?

6) What is the @after annotation in jnit Class for ?

7) List at Least 3 Assertion Type in junit

8) What is the first string parameter used in Assert methods ?

66
Day 5

Lab 1

Create the 3 Test Cases


ABC001 Go To Payment Gateway

ABC002 Generate a Purchase

ABC002-1 Generate a Purchase , Validate Credit Card Entry

ABC003 Search a Purchase

ABC004 Generate a Card Number *

ABC005 Make a Purchase from a Generated Credit Card *

67
Day 6

Lab 1

Create the 3 Test Cases


ABC001 Go To Payment Gateway

ABC002 Generate a Purchase

ABC002-1 Generate a Purchase , Validate Credit Card Entry

ABC003 Search a Purchase

ABC004 Generate a Card Number *

ABC005 Make a Purchase from a Generated Credit Card *

68
Day 7

Page Object Model


What is Page Object Model Design Pattern (POM)
https://www.softwaretestingmaterial.com/page-object-model/

Page Object Model is a Design Pattern which has become popular in Selenium
Test Automation. It is widely used design pattern in Selenium for enhancing
test maintenance and reducing code duplication. Page object model (POM)
can be used in any kind of framework such as modular, data-driven,
keyword driven, hybrid framework etc. A page object is an object-oriented
class that serves as an interface to a page of your Application Under Test.
The tests then use the methods of this page object class whenever they need
to interact with the User Interface (UI) of that page.
The benefit is that if the UI changes for the page, the tests themselves don’t
need to change, only the code within the page object needs to change.
Subsequently, all changes to support that new UI is located in one place.
69
Day 7

Object Oriented Design Principles

70
Day 7

Advantages of Page Object Model Framework


Code re-usability:
We could achieve code re-usability by writing the code once and use it in
different tests.

Code maintainability:
There is a clean separation between test code and page specific code such as
locators and layout which becomes very easy to maintain code. Code changes
only on Page Object Classes when a UI change occurs. It enhances test
maintenance and reduces code duplication.

Object Repository:
Each page will be defined as a java class. All the fields in the page will be
defined in an interface as members. The class will then implement the interface.

Readability:
Improves readability due to clean separation between test code and page
specific code
71
Day 7

Page Object Model

72
Day 7

Page Object Model


What is Page Object Model
Design Pattern (POM)

73
Day 7

Example HomePage
package tcs.pageob.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class UberHomePage {


WebDriver driver ;
//Using FindBy for locating elements
@FindBy(how=How.XPATH, using="//a[@id='1']") WebElement travelIcon ;
public UberHomePage(WebDriver driver) {

this.driver = driver;
}

public void clickTravelIcon() {

travelIcon.click();
}
}

74
Day 7
Example TravelPage

public class UberTravelPage {

WebDriver driver;
@FindBy(how=How.XPATH, using="//input[@name='pickup']") WebElement fromTravelInput;
@FindBy(how=How.XPATH, using="//a[@data-baseweb='button' and @aria-label='Pedir ahora']") WebElement requestTravelButton;

public UberTravelPage(WebDriver driver) {


this.driver = driver;
}

public void setfromTravelInput(String txt){


fromTravelInput.sendKeys(txt +Keys.ENTER);
}

public void clickRequestTravelButton(){


requestTravelButton.click();
}

75
Day 7
Example RequestTravelTest

@Test
public void test() {

UberHomePage homePageUber = PageFactory.initElements(driver, UberHomePage.class);


homePageUber.clickTravelIcon();

UberTravelPage uberTravelPage = PageFactory.initElements(driver, UberTravelPage.class);

uberTravelPage.setfromTravelInput("TATA 3");
uberTravelPage.clickRequestTravelButton();

76
Day 8
ReFactoring Test Cases of Lab

ABC001 Go To Payment Gateway

ABC002 Generate a Purchase

ABC002-1 Generate a Purchase , Validate Credit Card Entry

ABC003 Search a Purchase

ABC004 Generate a Card Number *

ABC005 Make a Purchase from a Generated Credit Card *

77
Day 9
Add Framework Cucumber - Gherkin

Gherkin is the format for cucumber specifications. It is a domain specific language


which helps you to describe business behavior without the need to go into detail of
implementation. This text acts as documentation and skeleton of your automated
tests.

This script serves two primary purposes:

Documents user scenarios


Writing an automated test (BDD)

78
Day 9
Add Framework Cucumber - Gherkin

79
Thank You.
80

You might also like