You are on page 1of 26

SELENIUM & TESTNG NOTES

Automation testing uses the specialized tools to automate the execution of manually designed
test cases without any human intervention. Automation testing tools can access the test data,
controls the execution of tests and compares the actual result against the expected result.
Consequently, generating detailed test reports of the system under test.

Automation testing is the best way to increase the effectiveness, efficiency and coverage of
software testing.

Selenium:

Selenium is an open-source (free) web UI automated testing suite for validating


web applications across multiple browsers and platforms. Selenium Test Scripts
can be written in a variety of programming languages, including Java, C#,
Python, and others. Selenium Testing is the term for testing done using the
Selenium testing tool.

Components of Selenium suite :


 Selenium Integrated Development Environment (IDE): It is a Firefox/Chrome
plug-in which have a “Record & playback feature” that is developed to speed up
the creation of automation scripts by recording the user actions on the web
browser and exporting them as a reusable script . It runs only in the Firefox
browser. Because of its simplicity, it cannot be used to create advanced and complicated
test cases.
 Selenium Remote Control (RC): It is usually Selenium-1 which has been
deprecated. It enables users to generate test scripts in their preferred
programming language against web-applications. RC server acts as a mediator
between selenium commands sent by test scripts & browser. It does require
separate installation of RC server which will interact with the browsers

Limitations of Selenium RC:


 Execution of test scripts is time-consuming as Selenium RC uses JavaScript commands
as instructions to the browser. This results in slow performance
 API’s are less object-oriented
 No support for Headless HTMLUnit browsers (Invisible browser)
SELENIUM & TESTNG NOTES

 Selenium WebDriver: It is a programming interface that helps create and run


test cases by directly communicating with the web browser and using its native
compatibility to automate. Unlike RC, it doesn’t require an additional server
installation to create and run test cases as it directly interacts with the browsers.
Test script execution is faster than Selenium RC as it makes direct calls to the
browser using browser drivers for a particular browser
 SELENIUM WEBDRIVER: Selenium Webdriver is an automation framework which
allows the user to execute tests for Web-applications across multiple browsers .It
supports multiple languages like C# , java, perl ,python and also can be run across
multiple platforms. It acts as an API, through which the automated test scripts ,selenium
commands are generated. For each commands, HTTP request is created and sent to
the browser drivers using HTTP server. This request results in implementation of scripts
in browser and browser sends the status back to HTTP server.
 Selenium WebDriver is an API provides communication facility between Client library and
browsers. It performs faster than RC, because unlike RC it directly communicates with the
server
 Architecture Of selenium:

Selenium language bindings/Client libraries:

1.Selenium developers have built language bindings/Selenium Client Libraries in order to


support multiple languages. These libraries are specific to the programming language
SELENIUM & TESTNG NOTES

used ,can be downloaded .A client library provides a programming interface to run


selenium commands.

JSON Wire Protocol over HTTP:


The client library then sends the commands or requests to the browser drivers. To carry
out this communication, WebDriver uses the JSON wire protocol.
JSON Wire Protocol provides a transport mechanism to transfer data between a server
and a client. 

 Selenium Grid: It allows parallel execution of tests on different browsers and


operating systems by distributing commands to different machines
simultaneously

RC- In this, Http proxy server was used.Scripts designed first communicates with proxy server and then
actions were performed in Web applications.If In case user has multiple testcases, so the execution time
will be very slow . Hence this is

Webdriver: no proxy http, scripts directly talks with the web based application

Selenium IDE: plugin for firefox , used for record & playback feature

Grid: its used for parallel execution of automated scripts across different platforms remotely on different
browsers simultaneously.

Limitations of selenium:

1. Doesn’t support desktop applications for automation

2. Cant generate good reports -à TestNG, extent reports concept

3. It cant read & write data in excel sheets by default-à Apache POI integration required

4. Junit/TestNG for organizing testcases (based on sanity & regression)

Selenium Webdriver: its an API which acts as a mediator

Webdriver API --àPackages à Classes--à methods(Packages them in .jar files)

Browser Drivers:
We know that Selenium runs in multiple browsers. Browser drivers help to run selenium scripts
on the browser. They act as a bridge that interprets the selenium commands to execute it in the
SELENIUM & TESTNG NOTES

browser. There are separate browser drivers for each browser, for example, ChromeDriver,
EdgeDriver, FirefoxDriver, InternetExplorerDriver, OperaDriver, SafariDriver, etc.

What is Webdriver interface ?


WebDriver is an interface. All the driver classes like FirefoxDriver, ChromeDriver,
InternetExplorerDriver, etc. are implementing the WebDriver interface. When a class
implements an interface, all the methods in the interface are also available in the implementing
class. The names of these methods are the same in all the classes, for example, the get method.

Interface Webdriver

{
SELENIUM & TESTNG NOTES

m1(){} ------ Method 1(No Body is present)

M2(){} ------Method 2(No method body is present)

Class FirefoxDriver Implements Webdriver

m1(){} ------ Method 1(Method Body is present)

M2(){} ------Method 2( method body is present)

Class ChromeDriver Implements Webdriver

m1(){} ------ Method 1(Method Body is present)

M2(){} ------Method 2( method body is present)

Selenium Locators:

Selenium identifies the elements on a Web Page using the  Locators. These locators are present
on the source page(HTML code) of a web page. In an HTML source code of a web page, all the
elements are defined with the help of tags and attributes. 
Name,ID, classname,Css Selector, Xpath, LinkText, partial link text

How to Identify the Web Element?

In Selenium, we have the WebElement interface that represents the HTML elements of a web


page. The WebElement interface consists of generic functions that help to interact with the
HTML elements. So how do we identify the Web element? 

In the WebDriver interface, we have a method, findElement(By.Locator()), which helps to


locate it. The findElement always selects the first web element using the given method. The
SELENIUM & TESTNG NOTES

method returns the WebElement interface reference. Let’s try an example for each of the
locators.

 Line no: 16:Here, findElement is a method in the WebDriver interface that returns the
WebElement reference. By is a class in Selenium, which has the mechanism to locate
elements. And, it has static methods in it. One of them is the id(java.lang.String id).

Xpath Locator:

Xpath represents the address of a HTML webelement on a web page . Xpath is an expression
or syntax in XML language which is used to find the element using HTML DOM
structure.There are two types of Xpath :
Absolute Xpath: The absolute Xpath is the complete address of the element starting from the
HTML tag. The absolute Xpath starts from the root tag, which is the HTML tag and, traverses
down till the element tag.
SELENIUM & TESTNG NOTES

Relative Xpath: It starts with ‘//’ double forward slash which means that it can search
webelement anywhere on the webpage.
Drawback of absolute Xpath: If any changes occur in the source code between the root HTML
element and the web element, the absolute Xpath stops working because of the changes.

Writing Custom Xpaths:


‘Contains’ & ‘text’ functions in Xpath:

//tagname[contains(text(),’text value’)] and //tagname[text()=’text value’]. Here, we are using


the contains function and the text function
Starts-with function:
//tagname[starts-with(@attribute,’constant value’)]
Ends-with function:

457_test, 568_test, 954_test 


//input[ends-with(@id,’_test’)].

Handling Dropdowns using Select Class: There are various types


of dropdowns available these days, majorly of which are categorized as a single-
select (which allows selecting only one value) or multi-select (which allows
selecting multiple values).
Selenium Webdriver provides a class named “Select” Class which provides various
methods to handle dropdowns either Single – select or multi-select . The objects
of Select type can be initialized by passing the dropdown webElement as
parameter to its constructor.

1. WebElement testDropDown = driver.findElement(By.id("testingDropdown"));  
2. Select dropdown = new Select(testDropDown);  

Important methods: To get the list of dropDown items :


 selectByIndex
 selectByValue
 selectByVisibleText
 deselectAll()
SELENIUM & TESTNG NOTES

 deselectByIndex()
 deselectByValue()
 deselectByVisibleText()

dropdown.getOptions(): returns List<webElement> of items found.


dropdown.getFirstSelectedOption(): return the selected item in dropdown
dropdown.getAllSelectedOptions(): Returns the list<> of all selected items in the
dropdown.isMultiple(): returns True/False , method, which determines whether the
dropdowns supports multiple selections

Handling JavaScript Alert and Popup in Selenium:


Alert is a message box which appears on the webpage , which gives some
information or warning message or asks the user for confirmation. Alerts
basically blocks the user to perform any action on the webpage unless it is
handled.
As we know, whenever we are executing any of the automation scripts using Selenium
WebDriver, the WebDriver always has the focus on the main browser window and will run all
the commands on the main browser window only. But, whenever an alert/popup appears,
it opens up a new window. So, for handling the Alerts using Selenium WebDriver, the focus
need to be shifted to the child windows opened by the Alerts. To switch the control from
the parent window to the Alert window, the Selenium WebDriver  provides the following
command:

driver.switchTo().alert();

Once we switch the control from the main browser window to the alert window,  we can
use the methods provided by  Alert Interface to perform various required actions. For
example, accepting the alert, dismissing the alert, getting the text from the alert window, writing
some text on the alert window, and so on.
SELENIUM & TESTNG NOTES

Types of alerts:
1.Simple Alert
2.Confirmation alert
3.Prompt alerts.

 We can handle the JavaScript popup using the Alert interface. It contains method to
switch to the alert box using the statement, Alert alert = driver.switchTo().alert(). Here,
the alert is the object reference. The above code moves the control on the alert box.
SELENIUM & TESTNG NOTES

 The next statement, alert.getText() gets the message text from the alert box. If we are
not using the object reference, then we can directly write the statement
as, driver.switchTo().alert().getText().
 Next, verify the text using the if-statement.
 Finally, the statement alert.accept() clicks the Ok-button. Similarly, to click on the
Cancel-button, we can use the statement, alert.dismiss().
 Without the object reference, the code can also be written
as driver.switchTo().alert().accept(), and driver.switchTo().alert().dismiss().

Handling multiple windows:

In selenium, sometimes we need to navigate to multiple windows to perform


certain tasks. This can be achieved in selenium by windows handlers.

Windows handle: It is unique identifier which holds the address of windows in


string form. Each browser window has unique windows handle.
driver.get("http://www.naukri.com/");
// It will return the parent window name as a String
String parent=driver.getWindowHandle();
Set<String>s=driver.getWindowHandles();
// Now iterate using Iterator
Iterator<String> I1= s.iterator();
while(I1.hasNext())
{
String child_window=I1.next();
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());
driver.close();
}
}
//switch to the parent window
driver.switchTo().window(parent);
}

Method Chaining in java: Chaining Methods, also known as Cascading, means


repeatedly calling one method after another on an object, in one continuous line of code .
public class DomNumber  
SELENIUM & TESTNG NOTES

{  
private int number;  
//creating a constructor   

DomNumber(int initialNum)  
{  
number=initialNum;  
}  
public DomNumber add(int toAdd)  
{  
number+=toAdd;  
//returns an instance of DomNumber  
return this;  
}  
//method to print the number  
public void print()  
{  
System.out.println(number);  
}  
}  
public class MethodChaining  
{  
public static void main(String args[])  
{  
DomNumber myNumber = new DomNumber(1);  
myNumber.add(5).print();  
}  

Output: 6
Handling Iframes in Webpage using selenium:

Frame is nothing but an HTML document embedded inside another HTML


document.

The iframes are mainly used to insert content from external sources. For


example, an advertisement displayed on a web page.

In order to perform some actions on any web element present inside the
Iframe, we need to switch the driver control to the frames. So ,for this purpose
we have method called SwitchTo().frame().This method throws
SELENIUM & TESTNG NOTES

NoSuchFrameException when the required frame is not found on the current


web page.

switchTo.frame(int  index number), switchTo.frame(string  frameNameOrId),


switchTo.frame(WebElement  frameElement)

switchTo().defaultContent() Vs switchTo().parentFrame()
method

 Switching back and forth between iframes and parent page can be
achieved using driver.switchTo().defaultContent() method.
 Please note that there is a similar method in Selenium to switch
between frames named driver.switchTo().parentFrame () method.
 The difference between driver.switchTo().defaultContent() and
driver.switchTo().parentFrame() is that the first method switches the
control to the main web page regardless of the number of frames
within the web page, while the second method switches the control
to the parent frame of the current frame.

JavaScriptExecuter in Selenium:

Selenium WebDriver basically allows us to perform various actions on the UI elements of


the webpage by sending selenium commands.But, there are scenarios where the
Webdriver commands will not work as expected due to various reasons. In these cases,
we take the help of JavaScriptExecutor.

JavaScriptExecutor is an interface provided by Selenium Webdriver, which presents a


way to execute JavaScript from Webdriver. This interface provides methods to run
JavaScript on the selected window or the current page. 

Syntax:

WebDriver driver = new ChromeDriver();


SELENIUM & TESTNG NOTES

JavaScriptExecuter js = (JavaScriptExecuter)driver;

Js.executeScript(“script”,””);

WebElement button =driver.findElement(By.className("button"));

JavaScriptExecuter js = (JavaScriptExecuter)driver;

js.executeScript("arguments[0].click();", button);

Generating alerts using javascriptExecuter:

js.executeScript("alert('Successfully Logged In');");

To Scroll vertically till some location:

js.executeScript(“window.scrollBy(0,500)”);

js.executeScript(“window.scrollBy(0,document.body.scrollHeight)”);

Clicking Radio Button using javascriptExecuter:


js.executeScript("document.getElementById('enter element id').checked=false;");

js.executeScript("document.getElementById('Email').value='SeleniumTesting.com';");

Actions class in selenium:


In selenium webdriver , we can perform basic operations like clicking a button , and entering
text on the textbox by using simple webElement commands WebElement.Click(),
WebElement.SendKeys() and WebElement.Submit(); for submitting the form.

However, there are complex interactions like Drag-n-Drop , Mouse-hover and Double-click
which cannot be done by simple WebElement commands.To achieve that selenium provides
“Actions” class. The Actions class contains a collection of actions that can be performed in
a web application.

1.Mouse actions
2.KeyBoard actions.

action.sendKeys(element, "iphone").build().perform();

action.sendKeys(Keys.ENTER).build().perform();
SELENIUM & TESTNG NOTES

Converting text to Uppercase:


action.keyDown(element,Keys.SHIFT).sendKeys("lambdatest").build().perform();

TakeScreenshot using selenium:


TakeScreenshot ts = (TakeScreenshot)driver;
File file = ts.getScreenshotAs(OutputType.FILE);
FileUtils.Copy(file, new file(“”));

Types of wait statements in Selenium:

For Selenium to efficiently act, there is a need for synchronization. It is the sync between
the Selenium script execution speed and the web application speed. The wait statements
SELENIUM & TESTNG NOTES

asks selenium webdriver to wait & pause the script execution for a certain length of time
until webelement appears.

While running Selenium tests, it is common for testers to get the message “Element Not Visible
Exception”. To overcome this issue, the wait statements are necessary.

Thread.sleep (ms) : It is a java method , its not a selenium webdriver . It is unconditional


method, and it pause the execution of the program for the mentioned amount of time
without any given condition.

There are three types of wait statements:

Implicit Wait, Explicit Wait, and Fluent Wait:


The implicit wait is a global wait that applies to all the web elements of a web page
to which the driver is interacting.
It tells the web driver to wait until a certain amount of time while trying to find an element
or elements that are taking time to load. In other words, it is applicable to all find element
commands. If the element does not load in the time mentioned in the implicit wait, it
throws an exception, No Such Element Exception. We use Implicit wait as soon as the
browser launches.

driver.manage().timeout().implicitlyWait(TimeOut,
TimeUnit.SECONDS);
SELENIUM & TESTNG NOTES

Sometimes Implicit wait fails in synchronization and, it becomes necessary to use Explicit
wait in such situations. Unlike Implicit wait, which applies to all the find element
commands, Explicit wait focuses on one particular element on the web page. Explicit wait is
concept of Dynamic wait, it tells the webdriver to wait or pause the execution until some
specific condition is validated successfully within maximum allowed time.
The Explicit wait tells the WebDriver to wait for a specific condition to be satisfied within
the maximum allowed time. If it fails, then throw an exception.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Wait.until(ExpectedConditions.VisibilityOfElementLocated(Wb));
 alertIsPresent()
 elementToBeClickable()
 visibilityOfElementLocated()

TESTNG: TestNG is an open-source testing framework inspired by Junit , used with


Selenium. It provides several features like data-driven testing, parameterization
support, running test cases in parallel, and test case grouping, etc.
It can be used for Unit, end to end , functional, Integration testing.
SELENIUM & TESTNG NOTES

Features of TestNG:

1. Different Types of Assertions


It has an Assert class that provides multiple methods supporting
different types of assertions. For instance, these assertions help in
checking equality of expected and actual result; asserting a
condition as True or False; asserting if a value is Null or not null,
etc.

2. Run tests in Parallel


Using its testNG.xml file, we can run test cases in parallel. This
helps in reducing the overall test execution time. The parallel
execution can be done in multiple levels – method level, class
level, suite level.

3. Make tests dependent on one another


We can make the test dependent on other tests. This can be done
with the help of the ‘dependsOnMethods’ and
‘dependsOnGroups’ attributes with @Test annotation.

4. Prioritizing tests
With this, we can assign a numerical priority value to the Tests.
The default priority is 0.

5. Grouping of tests
It supports the logical grouping of test cases. Thus, providing the
ability to run the test groups in parallel, performing certain
operations before or after the execution of the tests belonging to
a group.

6. Data-Driven Testing
Using @DataProvider, we can create data-driven tests. With this
dataProvider annotation, we can pass the test data to the test
method.
SELENIUM & TESTNG NOTES

7. Reporting
After test execution, an HTML report gets created providing
tabular reporting of test results. The reporting format is also
configurable by implementing listeners.

8. Parameterization
It provides inherent support for parameterization using its
@Parameters annotation. Using @Parameters annotation, we can
pass the value of a parameter to the test logic from the testng.xml
file.
 Advantages: It can be easily integrated with CI-CD tools like Jenkins.
This can be done with the help of the testNG.xml file.

 It helps in reducing overall test execution time by providing the


capability to run tests in parallel.

 We can make one test dependent on another. Thus, saving time by


skipping the dependent test in case the parent tests fail.

 With the grouping of tests, we can create different test suites like –
sanity, smoke, regression, etc. Moreover, we can integrate and trigger
those test suites with CI/CD tools like – Jenkins.

Running TestNG without main() method: When we create and run a


testng.xml or run using run() method of TestNG class, it internally builds a
suite of methods to be executed based on annotation provided to methods.

TestNG.class contains main() actually which calls suite internally to execute.


So, you do not need to write  main() method in a TestNG class to run it as
TestNG takes care of that by defining annotations. You just need to provide
proper annotations to methods and rest TestNG will execute them in a
manner by implicit call to main method of TestNG class.
SELENIUM & TESTNG NOTES

TestNG.xml file: It is a configuration file which has the information of


about the testcases that we want to execute ,how they will be executed’
So basically it controls the execution of testcases

TestNG Annotations:

Annotations are basically the tags used on the top of methods which gives
some additional information & helps to control the execution/flow of Test
cases.

@BeforeSuite,@AfterSuite,@BeforeTest,@AfterTest,@BeforeTest,@BeforeCl
ass,@AfterClass,
@BeforeMethod,@AfterMethod,@BeforeGroup,@AfterGroup,@DataProvid
er,@Parameters,@Factory,@Listeners,@Ignore

groups – Used to specify the groups, the test method belongs to.
@Test(groups = { "sanity", "regression" })

dataProvider – This attribute helps in creating a data driven tests. It is


used to specify the name of the data provider for the test.
@Test(dataProvider = "name of dataProvider")

alwaysRun – When set as True, the test method runs even if the
dependent methods fail.
@Test(alwaysRun=True)

dependsOnMethods – Used to specify the methods on which the test


method depends. The test method only runs after successful execution of the
dependent tests.
@Test(dependsOnMethods = { "dependentTestMethodName" })

TestNG Groups: TestNG groups allow us to perform grouping of different


testcases. The main purpose of grouping the testcases is to access the test
Methods from different classes
 @Test(groups= {"SmokeTest"})  
SELENIUM & TESTNG NOTES

 public void WebLoginPersonalLoan()  
 {  
     System.out.println("Web Login Personal Loan");  
 } 

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
3. <suite name="test_suite">  
4. <groups>  
5. <run>  
6. <include name="SmokeTest"/>  
7. </run>  
8. </groups>  
9. <test name="Personal Loan">  
10. <classes>  
11. <class name="com.javatpoint.Personal_loan"/>  
12. </classes>  
13. </test> <!-- Test -->  
14. <test name="Home Loan">  
15. <classes>  
16. <class name="com.javatpoint.Home_loan"/>  
17. </classes>  
18. </test> <!-- Test -->  
19. <test name="Car Loan">  
20. <classes>  
21. <class name="com.javatpoint.Car_loan"/>  
22. </classes>  
23. </test> <!-- Test -->  
24. </suite> <!-- Suite -->  

Disabling Testcases from TestNG.xml:


SELENIUM & TESTNG NOTES

1. <test name="Home Loan" enabled=”false”>  
2. <classes>  
3. <class name="com.javatpoint.Home_loan"/>  
4. </classes>  
5. </test> <!-- Test -->  

Parameters and Optional parameters: Parameters in TestNG is


similar to annotations in TestNG in their declaration. Similar to parameters in any
other programming language, they are declared to pass some values onto the
function. A simple reason to use parameters is that they let us run a function
many times with different values 

Parameters are basically the arguments passed on to the Test Methods. They are
passed via TestNG.xml file.

There are two ways to pass the parameters in TestNG:

 TestNG Parameters
 TestNG DataProviders

There is an issue with TestNG parameters. We can use them to pass the
parameters to test but this happens only once per test execution. We want to run
the specific test case with different set of parameters. Then Data providers came
into picture. DataProviders pass different values to the TestNG Test Case in a
single execution and in the form of TestNG Annotations. 

Suppose we want to set the global variables such url settings, username,
password or API Keys, there are some values which are constant in all the test
cases, in such case we use the TestNG Parameters.
SELENIUM & TESTNG NOTES

Optional parameters are yet another type of parameter which kind of acts like the
"default" attribute of the switch case in programming languages. So, if no
parameter value is specified, the optional parameter value is taken. Optional
parameters are those which are passed as arguments to the test methods only in
case No parameters are passed to methods.

Hard Assertions Vs Soft Assertions: A Hard Assertion is a type of


assertion that throws an exception immediately when an assert statement fails.
Test steps after hard assertion will not be executed and the next test in the test
suite will start.

We have all the assertions in Assert class,which has static methods like
assertEquals() etc. We can statically import the methods.

Soft Assertions are the type of assertions that do not throw an exception
immediately when an assertion fails. Therefore, all steps and soft assertions in the
automated test will execute before failing the test.

SoftAssert softAssert = new SoftAssert();


softAssert.assertEquals(actualUrl, expectedUrl, "Actual page url is not the same as expected");

TestNG Listeners: Listeners in TestNG annotations which “Listens” to the events


occurring during execution of test scripts. And perform some action based on the
events . They are applied as interfaces in the code.For example, the most common
usage of listeners occurs when taking a screenshot of a particular test that has
failed along with the reason for its failure. Listeners also help with logging and
generating results.

 The most commonly used listeners:


 ISuiteListener
SELENIUM & TESTNG NOTES

 ITestListener
 ITestListener: This is the most frequently used TestNG listener. ITestListener is
an interface implemented in the class , and that class overrides the ITestListener
defined methods. The ITestListener listens to the desired events and executes
the methods accordingly. It contains the following methods:
1. onStart(): invoked after test class is instantiated and before execution of any
testNG method.
2. onTestSuccess(): invoked on the success of a test
3. onTestFailure(): invoked on the failure of a test
4. onTestSkipped(): invoked when a test is skipped
5. onTestFailedButWithinSuccessPercentage(): invoked whenever a method
fails but within the defined success percentage
6. onFinish(): invoked after all tests of a class are executedThe above-mentioned
methods use the parameters ITestContext and ITestResult. The ITestContext is a
class that contains information about the test run. The ITestResult is an interface that
defines the result of the test.
Below is the configuration done in TestNG.xml file:

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

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite">

<listeners>

<listener class-name="MyListener"/>

</listeners>

<test name="Listeners_program">

<classes>

<class name="ItestListenerWithExample"></class>

</classes>
SELENIUM & TESTNG NOTES

</test>

</suite>

<!-- Suite -->

PAGE OBJECT MODEL(POM): Page Object Model is the design pattern of the Testing
framework which involves creating the page object repository for Web UI elements
of the Webpage. Under this page model , each page of the Web Application has a
corresponding java class which contains the action methods that needs to performed
on those web elements and a separate class which contains test methods. These java
classes act as a repository to store the various elements that we can interact with within
our test cases

POM Structure:
Class A
WebElements

Action methods

Test Methods
Class B

Applications:
 Reusability :The page class designed can be reused by other classes for
different testcases
 Easy Maintenance: If in future say , some UI element gets changed , then
the user has to make changes in the single class which contains the web UI
element.
SELENIUM & TESTNG NOTES

 More Readable.
Page Factory: Page Factory is enhanced version of POM design version. Page
factory is basically is a class provided by selenium to implement page object
model. In Page Factory, testers use @FindBy annotation.
The initElements method is used to initialize web elements.
@FindBy: An annotation used in Page Factory to locate and declare web elements using
different locators. Below is an example of declaring an element using @FindBy

@FindBy(id="elementId") WebElement element;

initElements(): is a static method in Page Factory class. Using the initElements method, one can
initialize all the web elements located by @FindBy annotation.

public class BrowserStackHomePage {

WebDriver driver;

@FindBy(xpath = "//h1") -------------------------------------------

WebElement Header;

@FindBy(xpath = "//*[@id='signupModalButton']")

WebElement getStarted;

public BrowserStackHomePage(WebDriver driver) {

this.driver = driver;

PageFactory.initElements(driver, this); ---------------------- Initialising the WebElements

POM Vs PageFactory :

1. In plain POM, you define locators using ‘By’ while in Page Factory, you use FindBy
annotation to define page objects.
2. Page Object Model is a design approach while PageFactory is a class which provides
implementation of Page Object Model design approach.
3. A Page Factory is one way of implementing PageObject Model which is inbuilt
in selenium.
SELENIUM & TESTNG NOTES

Desired Capabilities class in selenium:


Before releasing any web-application to the end-user, it is important to test it across
different environment.
Desired Capabilities is a class used to declare a set of basic requirements such as
combinations of browsers, operating systems, browser versions, etc. to perform
automated cross browser testing of a web application.
It is important to run a specific test across different environments. These
environments can be mobile devices, mobile browsers, desktop devices, desktop
browsers, screen resolutions, etc.
To declare these capabilities we use DesiredCapabilities class
It helps Selenium WebDriver set the properties for the browsers. So using different
capabilities from Desired Capabilities class we can set the properties of browsers. For
example, the name of the browser, the version of the browser, etc. We use these
capabilities as key-value pairs to set them for browsers.
Some of the important methods are like: setCapability(),getCapability(),
getBrowserName(),setBrowserName(),setVersion(),getVersion(),
setPlatform(),getPlatform().

Handling insecure certificates while launching the website on browser:


DesiredCapabilities cap = new DesiredCapabilities();
Cap.setAcceptInsecureCerts(true);
ChromeOptions opt = new ChromeOptions();
Opt.addArguments(“—disable-notifications”);
Opt.addArguments(“--incognito”);
Opt.merge(cap);
WebDriver driver = new ChromeDriver(Opt);

Logging using Log4j API:


Logging means providing state and information at runtime of execution of testcases.

You might also like