Selenium PDF
Selenium PDF
Selenium PDF
1
Introduction to Selenium (Notes By – Vaibhav Mhaskar)
Selenium is a free (open source) automated testing suite for web applications across different browsers and
platforms. Selenium is not just a single tool but a suite of software's, each software is for different testing needs
of an organization. It has four components.
1. Selenium (IDE)
3. Selenium WebDriver
4. Selenium Grid
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.
It came from a joke which Jason cracked one time to his team. Another automated testing framework was
popular during Selenium's development, and it was by the company called Mercury Interactive (yes, the
company who originally made QTP before it was acquired by HP). Since Selenium is a well-known antidote for
Mercury poisoning, Jason suggested that name. His teammates took it, and so that is how we got to call this
framework up to the present.
At the moment, Selenium RC and WebDriver are merged into a single framework to form Selenium 2.
Selenium 1, by the way, refers to Selenium RC.
Selenium IDE
Selenium Integrated Development Environment (IDE) is the simplest framework in the Selenium suite
and is the easiest one to learn. It is a Firefox plugin that you can install as easily as you can with other plugins.
However, because of its simplicity, Selenium IDE should only be used as a prototyping tool. If you want to
create more advanced test cases, you will need to use either Selenium RC or WebDriver.
2
Selenium Remote Control (Selenium RC)
Selenium RC was the flagship testing framework of the whole Selenium project for a long time. This is
the first automated web testing tool that allowed users to use a programming language they prefer. As of
version 2.25.0, RC can support the following programming languages: Java, C#, PHP, Python, Perl, and Ruby.
Selenium WebDriver
The WebDriver proves itself to be better than both Selenium IDE and Selenium RC in many aspects.
It implements a more modern and stable approach in automating the browser's actions. WebDriver, unlike
Selenium RC, does not rely on JavaScript for Automation. It controls the browser by directly communicating
with it. The supported languages are the same as those in Selenium RC : Java, C#, PHP, Python, Perl, Ruby.
Selenium IDE To learn about concepts on automated testing and Selenium, including.
2. Selenese commands such as type, open, clickAndWait, assert, verify, etc.
Locators such as id, name, xpath, css selector, etc.
Executing customized JavaScript code using runScript
Exporting test cases in various formats.
To create tests with little or no prior knowledge in programming.
To create simple test cases and test suites that you can export later to RC or
WebDriver.
To test a web application against Firefox only.
Selenium Grid To run your Selenium RC scripts in multiple browsers and operating systems
simultaneously.
To run a huge test suite, that needs to complete in the soonest time possible.
3
Summary
4
Selenium WebDriver (Notes By – Vaibhav Mhaskar)
Selenium WebDriver is a collection of open source APIs which are used to automate the testing of a web
application. Selenium WebDriver tool is used to automate web application testing scripts to verify that it works
as expected. In simple words WebDriver is a tool used to automate Browser operations.
WebDriver is an interface whose methods are implemented by RemoteWebDriver class whose child
classes are as follows - ChromeDriver, FirefoxDriver, IEDriver…. So on.
The Methods of WebDriver interface are classified into following three categories –
1. Control of browser
2. Selection of WebElements
3. Debugging aids
Some Methods of WebDriver Interface are –
5
6
Waits in Selenium (Notes By – Vaibhav Mhaskar)
Most of the web elements are written using Java script or AJAX
They may take certain amount of time to load on page.
In this situation chances of getting ‘NoSuchElementException’ are more.
To avoid such exceptions, Selenium has provided two types of Waits - Implicit Wait & Explicit Wait.
1. Implicit Wait:
This wait is set for the lifetime of WebDriver instance.
Wherever we use WebDriver instance before that line wait will be applied.
This wait, polls for 500milliseconds (This time depends on the browsers implementation class of webdriver. For
firefox it is 500milliseconds, it depends on type and version of browser).
If element becomes available in first 500milliseconds then element will be returned else it will wait for next 500
milliseconds. Our script will wait for max timeout.
We can specify default time out.
If element is not available in timeout value then ‘NoSuchElementException’ will be thrown.
We can specify timeouts in terms of: NanoSeconds, MicroSeconds, MilliSeconds, Seconds, Minutes, Hours and
Day.
E.g
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
In above example timeout value is 10 Seconds.
Now our script will wait for min 500 milliseconds and maximum 10 Second before each and every WebElement
that we wish to find using ‘driver’ instance.
Eg. -
In above example, our script will wait before clicking all three elements (Element1, Element2 and Element3 ).
7
Minimum wait time is 500milliseconds and maximum wait time is 10 seconds
2. Explicit Wait:
This wait is more customized than implicit wait.
We can apply this wait for particular web element.
We can even customize the polling time in explicit wait.
We can also ignore the exceptions that we don’t want while locating an element.
Same as implicit wait, we can set timeout for the web element.
We can also make our script wait until certain condition occurs.
We can achieve explicit wait using two classes of Selenium: FluentWait and WebDriverWait.
1. Using FluentWait:
FluentWait class implements Wait interface.
We can set our own timeout and polling time using FluentWait.
We can also ignore exceptions while waiting for particular WebElement.
We can wait till certain condition of a web element.
This wait can be applied to particular webelement unlike ‘Implicit Wait’ which applied for entire life
span of WebDriver instance.
8
In above example, wait is configured for maximum 10 seconds. If element is not available in 10 seconds, then
NoSuchElmentException will be thrown.
3. ignoring(exceptionType):
This method will ignore specific types of exceptions while waiting for a condition.
Eg.
wait.ignoring(NoSuchElementException.class);
4. until(ExpectedConditions):
After configuring wait using until() method, script will keep on waiting until one of the following encounters:
Until Expected condition is encountered.
Until the timeout expires
Until the current thread is interrupted
Eg.
wait.until(ExpectedConditions.alertIsPresent());
9
Above script will wait till alert is present on web page.
2. Using WebDriverWait:
WebDriverWait (WebDriver driver, Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut )
Interview Questions -
1. What are the types of waits available in Selenium WebDriver?
In Selenium we could see three types of waits such as Implicit Waits, Explicit Waits and Fluent Waits.
Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds) between each
consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when
the 30 seconds have elapsed after executing the previous test step/command.
Explicit Wait: Explicit waits are used to halt the execution till the time a particular condition is met or the
maximum time has elapsed. Unlike Implicit waits, explicit waits are applied for a particular instance only.
1. What is Implicit Wait in Selenium WebDriver?
Implicit waits tell to the WebDriver to wait for a certain amount of time before it throws an exception. Once we set the
time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is
0 (zero). We need to set some wait time to make WebDriver to wait for the required time.
3. Write a code to wait for a particular element to be visible on a page. Write a code to wait for an alert to appear.
We can write a code such that we specify the XPath of the web element that needs to be visible on the page and then ask
the WebDriver to wait for a specified time. Look at the sample piece of code below:
10
WebDriverWait wait=new WebDriverWait(driver, 20);
Similarly, we can write another piece of code asking the WebDriver to wait until an error appears like this:
Element = wait.until(ExpectedConditions.alertIsPresent());
FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check
the condition before throwing an “ElementNotVisibleException” exception.
1. Valids for life time of webdriver instance hence Can apply to particular web element
once used applicable to all elements
3. Polling time is browser & version specific and Polling time and timeouts is customizable.
fixed and timeouts is customizable.
4. this wait doesn’t provide a feature to wait till a this wait provides a feature to wait till a certain
certain condition occur condition occur
5. We can’t ignore any exception using implicit We can ignore exception using explicit Wait
Wait
There are basically two types of wait statements: Implicit Wait and Explicit Wait.
Implicit wait instructs the WebDriver to wait for some time by polling the DOM. Once you have declared implicit
wait, it will be available for the entire life of the WebDriver instance. By default, the value will be 0. If you set a longer
default, then the behavior will poll the DOM on a periodic basis depending on the browser/ driver implementation. Explicit
wait instructs the execution to wait for some time until some condition is achieved. Some of those conditions to be
attained are:
elementToBeClickable
elementToBeSelected
presenceOfElementLocated
7. What are the Expected Conditions that can be used in Explicit Wait ?
- The following are the Expected Conditions that can be used in Explicit Wait
1. alertIsPresent()
2. elementSelectionStateToBe()
3. elementToBeClickable()
4. elementToBeSelected()
5. frameToBeAvaliableAndSwitchToIt()
6. invisibilityOfTheElementLocated()
7. invisibilityOfElementWithText()
8. presenceOfAllElementsLocatedBy()
9. presenceOfElementLocated()
10. textToBePresentInElement()
11. textToBePresentInElementLocated()
12. textToBePresentInElementValue()
13. titleIs()
14. titleContains()
15. visibilityOf()
16. visibilityOfAllElements()
17. visibilityOfAllElementsLocatedBy()
18. visibilityOfElementLocated()
12
8. Can you write the syntax of Fluent Wait ?
FluentWait w = new FluentWait(driver);
w.withTimeout(10,TimeUnit.SECONDS);
13
Locators in Selenium (Notes By – Vaibhav Mhaskar)
Locators are used in selenium WebDriver to find an element on a DOM. Locating elements in Selenium
WebDriver is performed with the help of findElement() and findElements() methods provided by WebDriver
and WebElement class.
findElement() returns a WebElement object based on a specified search criteria or ends up throwing an
exception if it does not find any element matching the search criteria.
findElements() returns a list of WebElements matching the search criteria. If no elements are found, it
returns an empty list.
Example
<form name="loginForm">Login
14
1. Using id –
Each id is supposed to be unique couldn’t be duplicated. Which makes ids a very faster and reliable way
to locate elements. With id attribute value matching the location will be returned. If no element has a matching id
attribute, a “NoSuchElementException” will be raised.
All objects on a page are not having id attribute, it’s not realistic. In some cases developers make it having non-
unique ids on a page or auto-generate the ids, in both cases it should be avoided.
2. Using Name –
By using name attribute we can find element on DOM, name attributes are not unique in a page
all time. With the Name attribute value matching the location will be returned. If no element has a matching name
attribute, a “NoSuchElementException” will be raised.
3. Using Link –
With this you can find elements of “a” tags(Link) with the link names. Use this when you know link text
used within an anchor tag.
<a href="link.html">Name of the Link </a>
4. Using xPath –
While DOM is the recognized standard for navigation through an HTML element tree, XPath is
the standard navigation tool for XML and an HTML document is also an XML document (xHTML). XPath is
used everywhere where there is XML. Xpath has a fixed structure (syntax). See below –
15
By using following ways we can select username for above example :
Xpath = //*[@id=’username’]
Xpath = //input[@id=’username’]
Xpath = //form[@name=’loginForm’]/input[1]
Xpath = //*[@name=’loginForm’]/input[1]
Dynamic elements are those elements who changes is attribute on every runtime. Xpath Axes are used to find the
xpath of the such dynamic elements.
Xpath Axes –
XPath Axes are the methods used to find dynamic elements. XPath axes search different nodes in XML document
from current context node. XPath expression select nodes or list of nodes on the basis of attributes like ID , Name,
Classname, etc. from the XML document .
16
a) Following:
Selects all elements in the document of the current node( ) in following image, input box is the
current node.
There are 3 "input" nodes matching by using "following" axis- password, login and reset button. If you want to
focus on any particular element then you can use the below XPath method:
b) Ancestor: पर्ू वज
The ancestor axis selects all ancestors element (parent, grandparent,…etc.) of the current node as
shown in the below screen. In the below expression, we are finding ancestors element of the current node
("ENTERPRISE TESTING" node).
17
There are 13 "div" nodes matching by using "ancestor" axis. If you want to focus on any particular element then
you can use the below XPath, where you change the number 1, 2,3,…13 as per your requirement:
c) Child: Selects all children elements of the current node (Java) as shown in the below screen.
Xpath = //*[@id=’java_technologies’]/child::li
There are 71 "li" nodes matching by using "child" axis. If you want to focus on any particular element then You
can change the xpath according to the requirement by putting [1],[2]…………and so on.
Xpath = //*[@id=’java_technologies’]/child::li[1]
Select all nodes that come before the current node as shown in the below screen. In the below expression, it
identifies all the input elements come before "LOGIN" button that is Userid and password input element.
18
Xpath = .//*[@type = ‘submit’]//preceding::input
There are 2 "input" nodes matching by using "preceding" axis. If you want to focus on any particular
element then You can change the xpath according to the requirement by putting [1],[2]…………and so on.
Select the following siblings of the context node. Siblings are at the same level of the current node as shown in the
below screen. It will find the element after the current Login node . One input nodes matching by using "following-
sibling" axis
f) Parent: Selects the parent of the current node as shown in the below screen.
Xpath = //*[@id=’rt-feature’]//parent::div
19
There are 65 "div" nodes matching by using "parent" axis. If you want to focus on any particular element then
You can change the XPath according to the requirement by putting [1],[2]…………and so on.
g) Self:
Selects the current node or 'self' means it indicates the node itself as shown in the below screen. One node
matching by using "self " axis. It always finds only one node as it represents self-element.
h) Descendant:
Selects the descendants of the current node as shown in the below screen. In the below expression, it identifies all
the element descendants to current element ( 'Main body surround' frame element) which means down under the node
(child node , grandchild node, etc.).
There are 12 "link" nodes matching by using "descendant" axis. If you want to focus on any particular element
then You can change the XPath according to the requirement by putting [1],[2]…………and so on.
20
Xpath = //*[@id = ‘rt-fearture’]//descendant::a [1]
There is a debate on the performance of CSS Locator and XPath locator. Most of the automation testers believe that
using CSS selectors makes the execution of script faster compared to XPath locator. CSS Selector locator is always the best
way to locate elements on the page. CSS is always same irrespective of browsers.
In dynamic elements, there is always a part of locator which is fixed. We need to generate the locator using this
fixed part
<div>
<label class=”hidden-label” for=”Email”> Enter your email</label>
<input id=”Email” type=”email” autofocus=”” placeholder=”Enter your email” name=”Email”
spellcheck=”false” value=””> <input id=”Passwd-hidden” class=”hidden” type=”password” spellcheck=”false”>
</div>
21
Css = input#Email
If multiple elements have the same HTML tag and class, then the first one will be recognized.
Syntax: css=tag.class
<td>
<input id=”email“ class=”inputtext“ type=”email“ tabindex=”1“ value=”” name=”email“>
</td>
css=input.inputtext
If multiple elements have the same HTML tag and attribute, then the first one will be recognized. It acts in the
same way of locating elements using CSS selectors with the same tag and class.
Syntax: css=tag[attribute=value]
<div>
<label class=”hidden-label“ for=”Email“> Enter your email</label>
<input id=”Email“ type=”email“ autofocus=”” placeholder=”Enter your email“ name=”Email“ spellcheck=”false“
value=””> <input id=”Passwd-hidden“ class=”hidden“ type=”password“ spellcheck=”false“>
</div>
22
css = input[name=Email]
Syntax: css=tag.class[attribute=value]
<td>
<input id="email" class="inputtext" type="email" tabindex="1" value="" name="email">
</td>
css=input.inputtext[name=email]
SUB-STRING MATCHES:
CSS in Selenium has an interesting feature of allowing partial string matches using ^, $, and *.
Suppose
23
<input="Employee_ID_001">
Starts with (^): To select the element, we would use ^ which means ‘starts with’
css=input[id^='Em']
Ends with ($): To select the element, we would use $ which means ‘ends with’.
css=input[id^=’001’]
Contains (*): To select the element, we would use * which means ‘sub-string’
css=input[id*='id']
Css = "input:contains('id')"
Syntax: parentLocator>childLocator
Explanation: ‘div#buttonDiv>button’ will first go to div element with id ‘buttonDiv’ and then select its child
element – ‘button’
24
Explanation: ‘div#buttonDiv button’ will first go to div element with id ‘buttonDiv’ and then select ‘button’
element inside it (which may be its child or sub child)
<ul id="automation">
<li>Selenium</li>
<li>QTP</li>
<li>Sikuli</li>
</ul>
css="ul#automation li:nth-of-type(2)"
Similarly, To select the last child element, i.e. ‘Sikuli’, we can use
css="ul#automation li:last-child"
25
Alert Handling (Notes By – Vaibhav Mhaskar)
What is Alert?
Alert is a small message box which displays on-screen notification to give the user some kind of information or ask
for permission to perform certain kind of operation. It may be also used for warning purpose.
1) Simple Alert -
2) Prompt Alert - This Prompt Alert asks some input from the user and selenium webdriver can enter the
text using sendkeys(" input…. ").
3) Confirmation Alert - This confirmation alert asks permission to do some type of operation.
26
How to handle Alert in Selenium WebDriver ?
Alert interface provides the below few methods which are widely used in Selenium Webdriver.
Example Code -
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.Alert;
public class AlertDemo {
public static void main(String[] args) throws NoAlertPresentException,InterruptedException {
System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://demo.guru99.com/test/delete_customer.php");
driver.findElement(By.name("cusid")).sendKeys("53920");
driver.findElement(By.name("submit")).submit();
Alert alert = driver.switchTo().alert(); // Switching to Alert
String alertMessage= driver.switchTo().alert().getText(); // Capturing alert message.
System.out.println(alertMessage); // Displaying alert message
Thread.sleep(5000);
alert.accept(); // Accepting alert
}
}
27
iframes Handling (Notes By – Vaibhav Mhaskar)
iFrame is a HTML document embedded inside an HTML document. iFrame is defined by an <iframe>
</iframe> tag in HTML. With this tag you can identify an iFrame while inspecting the HTML tree.
Here is an sample HTML code of a HTML page which contains two iFrames :
<html>
<body>
<div class="box">
<iframe name="iframe1" id="IF1" height="600" width="400" src="http://toolsqa.wpengine.com"></iframe>
</div>
<div class="box">
<iframe name="iframe2" id="IF2" height="600" width="400" align="left" src="htp//demoqa.com"></iframe>
</div>
</body>
</html>
To Switch between iFrames we have to use the driver’s switchTo().frame command. We can use
the switchTo().frame() in three ways:
1. switchTo.frame(int frameNumber): Pass the frame index and driver will switch to that frame.
2. switchTo.frame(string frameNameOrId): Pass the frame element Name or ID and driver will switch to that
frame.
3. switchTo.frame(WebElement frameElement): Pass the frame web element and driver will switch to that frame.
There are two ways to find total number of iFrames in a web page. First by executing a JavaScript and second is by
finding total number of web elements with a tag name of iFrame. Here is the code using both these methods:
28
Switching on iFrames
Sample Program -
29
Cookies Handling (Notes By – Vaibhav Mhaskar)
Cookies are small files which are stored on a user's computer. They are designed to hold a modest amount of data
specific to a particular client and website, and can be accessed either by the web server or the client computer. This allows
the server to deliver a page tailored to a particular user, or the page itself can contain some script which is aware of the data
in the cookie and so is able to carry information from one visit to the website (or related site) to the next.
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandlingCookies {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "F:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.amazon.in");
Set <Cookie> cookies = driver.manage().getCookies(); // getting all cookies
System.out.println("size of cookies : "+ cookies.size()); // printing cookies total size
for (Cookie cookie : cookies) {
Sopln(cookie.getName() + " : " + cookie.getValue()); // printing all cookies with value
}
Sopln(driver.manage().getCookieNamed("csm-hit")); // getting "csm-hit" cookie
Cookie cookieObj = new Cookie("myCookie","12345"); // creating obj og cookie to add new cookie
driver.manage().addCookie(cookieObj); // adding cookie
Set <Cookie> cookies1 = driver.manage().getCookies(); // after adding cookie getting all cookie
for (Cookie cookie : cookies1) {
Sopln(cookie.getName()+" : "+ cookie.getValue()); // printing all cookies
}
driver.manage().deleteCookie(cookieObj); // deleting cookie
cookies1 = driver.manage().getCookies();
Sopln("size of cookies : "+ cookies.size()); // printing size of a cookies after deleting cookie
for (Cookie cookie : cookies1) {
Sopln(cookie.getName()+" : "+cookie.getValue()); // printing all cookies
}
driver.quit();
}}
30
Actions Class of Selenium WebDriver (Notes By – Vaibhav Mhaskar)
6 keyDown(modifier_key) Press the modifier key, doesn’t release the modifier key press, subsequent
interactions may assumed, it is kept pressed.
31
Example Code 1 – Entering the text
Example Code 2 –
32
Robot Class in Java (notes By – Vaibhav Mhaskar)
In certain Selenium Automation Tests, there is a need to control keyboard or mouse action to interact with
OS windows like Download pop-up, Alerts, Print Pop-ups, etc. or native Operation System applications like
Notepad, Skype, Calculator, etc.
Selenium WebDriver cannot handle these OS pop-ups / applications. In Java version 1.3 Robot Class was
introduced. Robot Class can handle OS pop-ups/applications. Robot class is present in AWT package of JDK.
Advantages -
Robot Class methods can be used to interact with keyboard / mouse events while doing browser
automation. Alternatively AutoIT can be used, but its drawback is that it generates an executable file (exe)
which will only work on windows, so it is not a good option to use.
robo.keyPress(KeyEvent.VK_DOWN);
robo.keyPress(KeyEvent.VK_ENTER);
5. To move Mouse Pointer of mouse
robo.mousePress(InputEvent.BUTTON1_DOWN_MASK);
7. To release left Mouse Button of mouse
robo.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
1. Keyword / mouse event will only works on current instance of Window. E.g. suppose a code is
performing any robot class event, and during the code execution user has moved to some other screen then
keyword / mouse event will occur on that screen.
2. Most of the methods like mouseMove is screen resolution dependent so there might be a chance that code
working on one machine might not work on other.
Example Code –
Selenium uses WebDriver API and sends commands to browser driver to perform actions (through the
"JSON wire protocol"). However, Java AWT Robot uses native system events to control keyboard and mouse
operations. If your aim is, browser automation, then technically you don't need to use Robot framework because
the Actions() functionality provided by Selenium is more than enough. But of course, there are cases when
browser or native OS popup comes up like uploading/ downloading a file. This can also be solved using Robot
framework- though generally there are selenium-specific solutions/workarounds that can help avoiding using
Robot. The key idea of these workarounds is "since we cannot control the popups, just don't let them open".
For instance, while downloading a file in Firefox, you will get a popup asking you to choose a location
and filename where it should get saved. This kind a situation cannot be manipulated using selenium. But, however
what you can do is, let Firefox know for certain file types, where to save the downloads automatically, without
handling the popup.
Robot class is a java based utility which emulates the keyboard and mouse actions. The Actions class is
selenium based utility, user-facing API for emulating complex user action events
Simply we can say that Java AWT Robot class is useful to handle OS windows like AutoIT
whereas Action class is not meant to Automate OS windows.
35
AutoIT (Notes By – Vaibhav Mhaskar)
Suppose we have to upload an image file i.e. photo after clicking on Choose File Button.
After Clicking on Choose Button following window based app’s “open” window will appear which we can’t
automate using selenium WebDriver. Here AutoIT comes in picture. To automate Window based app we need
to use AutoIT.
In order to automate window based app we need to download AutoIT application. i.e. AutoIT Editor and
AutoIT Element Finder. Download from following links and install on your system:
36
AutoIT - SciTE4AutoIt3.exe : https://www.autoitscript.com/site/autoit-script-editor/downloads/
After successful installation please go to the following path on your system where can find the editor and
locator
Now let’s see How to search elements details for a desktop app automation script
37
1) Click on Choose File button to Upload the file (this action will be atomized by selenium webdriver ),
after clicking following widow will appear on screen whose elements details we require in desktop app
automation script. Details are – title, text, controlID etc.
2) In following window we are going to search specific file. We just enter the path of desired file in File
Name box.
3) In order to do so, we need to focus of automation tools attention on a File name box by following way
– Drag and drop Finder Tool on desired element whose details we need.
38
4) Then, AutoIt v3 Window Info (Element Finder) window will get filled with the details –
Title : Open
Class : Edit
Instance : 1
controlID : Edit1
ControlFocus("Open","",EditBox1);
5) And by using following command in Script Editor we are able to enter text i.e. path of file to be
uploaded. 2nd command in Script Editor will be :
ControlSetText("Open","","Edit1","F:\IMG_2095 - Copy.JPG")
//here “text” parameter kept blank, surrounded by double quote, i.e. “”
6) Simillarly , Now do all above steps for open Button and find details, Drag and drop finder tool on open
Button.
39
title : Open,
contrilID : Button1
Sleep(500)
ControlFocus("Open","","Edit1") //Sets input focus to a given control on window
Sleep(500)
ControlSetText("Open","","Edit1","F:\Donald Trump.jpg") // sets test of a control
Sleep(500)
ControlClick("Open","","Button1") //sends a mouse click command to a given control
Sleep(500)
9) and compile the code. click on tools and then click on compile then following window will appear
In selenium script after clicking on “Choose file” button we have to run xxxxxxx.exe file in order to execute
window app automation script by using following command –
40
Selenium Script -
41
Java Script & JavaScriptExecuter (I) (Notes By – Vaibhav Mhaskar)
JavaScript is the programming language of HTML and the Web. JavaScript used to program the behavior of web
page. JavaScriptExecutor is an interface of Selenium. It is used to change appearance of HTML coded webpage on a client
end. Usually we design webpages using JavaScript. JavaScript written in console of a Browser. JavaScript is a programming
language which is used –
to handle elements on entire document object model (HTML document)
Click on Element
to enter the text in TextBox
to select values from dropdown menu
to handle alert
to handle window (scrolling, Minimising, Maximizing, Closing ..)
There are two classes in JavaScript which are required to automate webpages.
1) Document Class –
This class refers to entire HTML DOM. We can perform different operations like click, enter text, select
from dropdown, change visibility of webElement, change colour of webElement etc. using this class.
Some Methods of Document class –
Sr. Property/Method Description Syntax
No
1 Cookie Returns all name/value pairs of 1. document.cookie // return cookie property
cookies in the document 2. document.cookie = newCookie // set new cookie
2 fullscreenEnebled() Return a Boolean value indicating Document.fullscreenEnabled
whether the document can viewed in
full screen mode
3 fullscreenElement Return the current element that is var ele = fullscreenElement ;
displayed in full screen mode
4 getElementById() Returns the element that has id document.getElementById(“demo”);
attribute with the specified value
5 getElementByClassName() Returns a node list containing all var x =
elements with the specified class document.getElementsByClassName(“example”);
name
6 getElementsByName() Returns a node list containing all var x = document.getElementsByName(“fname”);
elements with a specified name
7 getElementByIdTageName() Returns a node list containing all var x = document.getElementsByTagName(“Li”);
elements with the specified tag name
8 Title Sets or returns the title of the
document
9 Images Returns a collection of all <img> var x = document.images.length;
elements in the document
10 write() Writes HTML expressions or document.write(“Hello World”);
JavaScript code to a document
11 writeln() Same as write(), but adds a newline document.writeln(“Hello World”);
character after each statement
13 URL Returns the full URL of the HTML var x = document.URL;
Document
14 Scripts Returns the collection of (script) var x = document.scripts.length;
elements in the documents
42
2) Window Class -
The window object represents an open window in a browser. If a document contain frames (<iframe>
tags), the browser creates one window object for the HTML document, and one additional window object for each
frame.
JavaScriptExecuter --
JavaScriptExecutor is an interface that helps us to execute Java Script through Selenium Webdriver.
In Selenium Webdriver, locators like XPath, CSS, etc. are used to identify and perform operations on a web page.
In case, these locators do not work you can use JavaScriptExecutor. You can use JavaScriptExecutor to perform a desired
43
operation on a web element. Selenium supports javaScriptExecutor. There is no need for an extra plugin or add-on. You
just need to import org.openqa.selenium.JavascriptExecutor in the script as to use JavaScriptExecutor.
It has following two methods to run JavaScript on current window or on selected window.
1. ExecutesAsynchScript(Script, Argument) –
With Asynchronous script, your page renders more quickly. Instead of forcing users to wait for a script to
download before the page renders. This function will execute an asynchronous piece of JavaScript in the context
of the currently selected frame or window in Selenium. The JavaScript so executed is single-threaded with a various
callback function which runs synchronously.
2. ExecuteScript(Script, Argument) –
This method executes JavaScript in the context of the currently selected frame or window in Selenium. The
script used in this method runs in the body of an anonymous function (a function without a name). We can also
pass complicated arguments to it.
Boolean
Long
String
List
WebElement
NOTE : To use JavaScript Executer we need to type caste driver instance into JavaScript executer
44
Example 2 – Scrolling down using JavaScript ( Interview question )
System.setProperty("webdriver.chrome.driver","F:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.facbook.com");
JavascriptExecutor js = (JavascriptExecutor) driver ;
js.executeScript("window.scrollBy(0,100)"); // scrolling down by 100
Thread.sleep(1000);
js.executeScript("window.scrollBy(0,100)"); // scrolling down by 100
Thread.sleep(1000);
js.executeScript("window.scrollBy(0,-200)"); // scrolling up by -200
}}
45
TestNG (Test Next Generation) (Notes By – Vaibhav Mhaskar)
1. TestNG Introduction
2. TestNG Annotations And Benefits
3. To Create TestNG.xml file
4. Ignore Tests in TestNG
5. Skip Test In TestNG
6. Groups
7. Exception
8. Dependencies
9. Parameterized Tests Using XML
10. Parameterized Tests Using DataProviders
11. Parallel Execution in TestNG
12. Asserts
13. Soft Assert
14. Listeners
15. IRetryAnalyzer – How To Run Failed Test Cases
16. TestNG Reports
17. How To Run TestNG Using Command Prompt
18. TestNG Reporter logs
46
TestNG (Test Next Generation)
1. TestNG Introduction
TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing to
integration testing. Writing a test is typically a three-step process:
A) Write the business logic of your test and insert TestNG annotations in your code.
B) Add the information about your test (e.g. the class name, the groups you wish to run, etc) in a testng.xml file
C) Run TestNG.xml.
3 @AfterMethod A method which is marked with this annotation will be executed after
every @test annotated method.
4 @BeforeClass A method which is marked with this annotation will be executed before first
@Test method execution. It runs only once per class.
5 @AfterClass A method which is marked with this annotation will be executed after all the
@Test methods in the current class have been run
6 @BeforeTest A method which is marked with this annotation will be executed before first
@Test annotated method.
7 @AfterTest A method which is marked with this annotation will be executed
when all @Test annotated methods complete the execution of those classes
which are inside <test> tag in testng.xml file.
8 @BeforeSuite A method which is marked with this annotation will run only once before all
tests in the suite have to run
9 @AfterSuite A method which is marked with this annotation will run once after execution
of all tests in the suite have run
10 @BeforeGroups This annotated method will run before first @test run of that specific group.
11 @AfterGroups This annotated method will run after all @test methods of that group
completes its execution.
12 @Parameters This annotation is used to pass parameters to test methods.
13 @Listeners This annotation is used with test class. It helps in writing logs and results.
14 @ Factory Marks a method as a factory that returns objects[ ] that will be used by TestNG
as Test classes. The method must return Object[ ].
15 @DataProvider we use @DataProvider annotation for data supplier method which return
Object[][]. which we can use in @Test annotated method. The @Test method
that wants to receive data from this DataProvider needs to use a dataProvider
name equals to the name of this annotation.
47
Test – is a group of Test Cases (we may call it class) & Test Cases – is a group of Test Steps i.e. methods
Note –
Class level Annotations are @Test, @ignore, @Listeners rest of the all annotations are method level, if
we write @Test on the top of class then all the methods inside that class will be treated as test cases & they will
appear in emailable-report.html file as test cases, if we write @ignore on top of class then all the methods of that
class will be excluded from execution.
In TestNG framework, we need to create Testng xml file to create and handle multiple test classes. We
do configure our test run, set test dependency, include or exclude any test, method, class or package and set
priority etc in the xml file.
Right click on Project folder, go to New and select ‘File‘ as shown in below image
In New file wizard, add file name as ‘testng xml‘ as shown in below given image and click
on Finish button.
<suite>
<test>
<Classes>
<class name=".test"/>
<class name="…......>
< .....
</Classes>
</test>
</Suite>
Note: You can choose any name for your Test Suite & Test Name as per your need. Format of class name is -
class name = PackageName.ClassName
48
Run the test by right click on the testng.xml file and select Run As > TestNG Suite. After
execution you may check the output on console.
There is one more way to create testng.xml file in your project. It is most easy and simple way. After complete
creation of your project just do following sequence
<suite name="Suite">
<listeners>
<listener class name="com.thc.cases.manageNursePageTest"/ >
</listeners>
<test thread-count="5" name="Test">
<classes>
<class name="com.thc.cases.manageNursePageTest"/>
<class name="com.thc.cases.LoginPageTest"/>
<class name="com.thc.cases.PatientHomePageTest"/>
<class name="com.thc.cases.DoctorAddListPageTest"/>
<class name="com.thc.cases.AdminHomePageTest"/>
<class name="com.thc.cases.DoctorHomePageTest"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
We may include or exclude any test or method from tetsng.xml file In 3 ways,
1) By typing annotations (enabled= false) in a java code over any test or method
2) By excluding it in xml file
Code - TestNG.xml -
package softwareTestingMaterial;
import org.testng.annotations.Test;
@ignore
public class TestCase2 {
@Test
public void printClass2(){
System.out.println("This is Test Case 2");
} }
Note - There are three annotations which can be written on class level they are @test, @ignore, @Listeners rest
of the all annotations are method level, if we write @Test on the top of class then all the methods inside that class
will be treated as test cases & they will appear in emailable-report.html file as test cases, if we write @ignore on
top of class then all the methods of that class will be excluded from execution
One way of skipping a test method is by using throw new SkipException() exception. Once
SkipException() thrown, remaining part of that test method will not be executed and control will goes directly to
next test method execution. Let’s see Example code
public class SkipTestCase {
@Test
public void aSkipTest(){
String a ="Skip Test";
if(a.equals("Skip Test")){
throw new SkipException("Skipping - This is not ready for testing ");
}else{
System.out.println("I am in else condition");
}
System.out.println("I am out of the if else condition");
}
@Test
public void nonSkipTest(){
System.out.println("No need to skip this test");
} }
Output on Console –
No need to skip this test
PASSED: nonSkipTest
SKIPPED: aSkipTest
============================
Default suite
Total tests run: 2, Failures: 0, Skips: 1
============================
50
6. TestNG Groups
TestNG allows you to perform groupings of test methods. We can also specify groups that contain other
groups. Groups are specified in testng.xml file and can be found either under the <test> or <suite> tag. Groups
specified in the <suite> tag apply to all the <test> tags between it.
Groups can also include other groups. These groups are called MetaGroups. For example, you might
want to define a group all that includes smokeTest and functionalTest. Let’s modify our testng.xml file as
follows:
51
Group of Groups: Console Output:
testng.xml :
52
7. TestNG Exception
Console Output :
[TestNG] Running:
SoftwareTestingMaterial.com
============================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
============================
The expected exception to validate while running the below test is mentioned using the expectedExceptions
attribute value while using the @Test annotations. See following example
53
Console Output:
[TestNG] Running:
SoftwareTestingMaterial.com
============================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
============================
8. TestNG Dependencies:
TestNG allows you to specify dependencies either with annotations or in XML. TestNG allows you to specify
dependencies either with:
Console Output:
[TestNG] Running:
Test Case 1
Test Case 2
============================
softwaretestingmaterial
Total tests run: 2, Failures: 0, Skips: 0
============================
54
Now we add the ‘dependsOnMethods’ attribute to the @Test Annotations and execute the same program.
Execute the same testng.xml which was placed above and see the difference in Console Output
Console Output:
[TestNG] Running: Test Case 2 executed first and the Test Case 1
Test Case 2
Test Case 1
============================
softwaretestingmaterial
Total tests run: 2, Failures: 0, Skips: 0
============================
Examle Code :
package TestingMaterial;
import org.testng.annotations.Test;
public class DependsOnMethodsTestCase {
@Test(groups = { "FirstGroup" })
public void testCase1() {
Sopln("Test Case 1");
}
@Test(groups = { "SecondGroup" })
public void testCase2() {
System.out.println("Test Case 2");
} }
55
Testng.xml : <suite name="Testingmaterial">
<test name="testngTest">
<groups>
<dependencies>
<group name="FirstGroup" dependson="SecondGroup"></group>
</dependencies>
</groups>
<classes>
<class name="softwareTestingMaterial.DependsOnMethodsTestCase" />
</classes>
</test>
</suite>
Console Output:
[TestNG] Running:
Test Case 2
Test Case 1
============================
softwaretestingmaterial
Total tests run: 2, Failures: 0, Skips: 0
============================
From above console output it is clear that method assigned to dependsOn is executed first then
dependent Method
Parameterized tests allow developers to run the same test again and again using different values. There are two
ways to set these parameters:
with testng.xml
with Data Providers
With this technique, we could define the parameters in the testng.xml file and then reference those parameters
in the source files.
56
Create a java test class, say, ParameterizedTest.java
Add test method parameterizedTest() to your test class. This method takes a string as input parameter
Add the annotation @Parameters(“browser”) to this method. The parameter would be passed a value from
testng.xml, which we will see in the next step.
Code TestNG.xml
Here, name attribute represents the parameter name and value represents the value of that parameter. We
could use this parameter to the test method parameterizedTest by using @Parameters(“browser”) as mentioned
in the above step.
[TestNG] Running:
=============================
softwaretestingmaterial
Total tests run: 1, Failures: 0, Skips: 0
=============================
Note : TestNG will automatically try to convert the value specified in testng.xml to the type of your parameter.
Here are the types supported:
String double/Double
int/Integer float/Float
boolean/Boolean long/Long
byte/Byte short/Short
char/Character
57
10. Parameterized Tests Using DataProviders –
Specifying parameters in testng.xml might not be sufficient if you need to pass complex parameters, or
parameters that need to be created from Java (complex objects, objects read from a property file or a database,
etc…). In this case, you can use a Data Provider to supply the values you need to test. A Data Provider is a
method in your class that returns an array of objects. This method is annotated with @DataProvider:
UserName is FirstUid
Password is FirstPWD
UserName is SecondUid
Password is SecondPWD
============================
softwaretestingmaterial
Total tests run: 2, Failures: 0, Skips: 0
============================
There are situations where we want to run multiple tests with same or different browsers at the same
time. In such cases, we can use “parallel” attribute in testng.xml to accomplish parallel test execution in
TestNG.
58
The parallel attribute of suite tag can accept four values:
tests – All the test cases inside <test> tag of testng.xml file will run parallel
classes – All the test cases inside a java class will run parallel
methods – All the methods with @Test annotation will execute parallel
instances – Test cases in same instance will execute parallel but two methods of two different instances will
run in different thread.
In the below program, I took two methods. First methods opens Firefox driver and navigate to
http://www.SoftwareTestingMaterial.com and closes the browser. Second methods opens Chrome driver and
navigate to the same URL and closes the browser.
@Test
public void getChorme(){
System.setProperty("webdriver.chrome.driver", "D://chromedriver.exe");
Sopln("GetChrome is running on Thread : " + Thread.currentThread().getId());
WebDriver driver = new ChromeDriver();
driver.get("http://www.SoftwareTestingMaterial.com");
driver.close();
}
}
TestNG.xml file -
</suite>
59
Once you run the testng.xml using the above code, you could see both the browsers in action at a time.
Here in the above testng.xml file, I have passed parallel=methods and thread-count=2 at the suite level. I
would like to execute selenium scripts in parallel in different threads. Most of the times, these two methods will
execute in different threads. Thread Id may vary on every run. Here we are just passing thread count but we are
not assigning any thread id, assigning thread id will be taken care by your system processor.
TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the
TestNG Assertions, we will consider a successful test only if it is completed the test run without throwing any
exception.
Assert.assertEquals(driver.getTitle(), actualTitle);
Example Code
60
Different TestNG Asserts Statements:
Assert.assertEqual(String actual, String expected) :Asserts that two Strings are equal. If they are not,
an AssertionError is thrown.
Parameters:
actual – the actual value
expected – the expected value
Assert.assertEqual(String actual, String expected, String message) : Asserts that two Strings are equal.
If they are not, an AssertionError, with the given message, is thrown.
Parameters:
actual – the actual value
expected – the expected value
message – the assertion error message
Assert.assertEquals(boolean actual, boolean expected) : Asserts that two Booleans are equal. If they
are not, an AssertionError is thrown.
Parameters:
actual – the actual value
expected – the expected value
Parameters:
condition – the condition to evaluate
Parameters:
condition – the condition to evaluate
message – the assertion error message
Parameters:
condition – the condition to evaluate
61
Parameters:
condition – the condition to evaluate
message – the assertion error message
There are two types of Assert Hard Assert & Soft Assert
Hard Assert –
Hard Assert throws an AssertException immediately when an assert statement fails and test suite
continues with next @Test. The disadvantage of Hard Assert – It marks method as fail if assert condition gets
failed and the remaining statements inside the method will be aborted.
Soft Assert –
Soft Assert collects errors during @Test. Soft Assert does not throw an exception when an assert fails and would
continue with the next step after the assert statement. If there is any exception and you want to throw it then you
need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as
it is.
We need to create an object to use Soft Assert which is not needed in Hard Assert. Here we took two
methods namely softAssert() and hardAssert().
In the softAssert() method, we have used SoftAssert class and intentionally passing value false in the assertTrue()
method to make it fail & In the hardAssert() method, we simply used Assert and intentionally passing parameter
value false in the assertTrue() method to make it fail.
Note: If you forget to call assertAll() at the end of your test, the test will pass even if any assert objects threw
exceptions as shown in the above example. So don’t forget to add assertAll().
Execute the above script and see the console output. There are two failures here. Second failure is due
to assertAll()method
@Override
public void onStart(ITestContext context) { }
@Override
public void onFinish(ITestContext context) { }
}
Step 2: Create another Class “ListenerTestNGTestCase” and write a script (which ever script you prefer). Else
copy paste the below mentioned script.
Step 3: Add the listeners annotation (@Listeners) in the Class “ListenerTestNGTestCase”.The complete
“ListenerTestNGTestCase” class after adding Listener annotation is mentioned below:
64
@Listeners(listeners.ListenerTestNG.class)
public class ListenerTestNGTestCase {
WebDriver driver= new FirefoxDriver();
// Test to pass as to verify listeners .
@Test(priority=1)
public void TestToPass()
{
System.out.println("This method to pass test");
driver.get("https://www.softwaretestingmaterial.com/");
driver.getTitle();
driver.quit();
}
//Used skip exception to skip the test
@Test(priority=2)
public void TestToSkip ()
{
System.out.println("This method to skip test");
throw new SkipException("Skipping - This is not ready for testing ");
}
// In the above method, we have already closed the browser.
So we couldnot get the title here. It is to forcefully fail the test
@Test(priority=3)
public void TestToFail()
{ driver.getTitle();
System.out.println("This method to test fail");
}}
Step 4: Execute the “ListenerTestNGTestCase” class. Methods in class “ListenerTestNG” are called
automatically according to the behavior of methods annotated as @Test.
Step 5: Verify the Output in the console. You could find the logs in the console. Add the bold lines of code in
the TestNG.xml file shown below. –
<suite name="Suite">
<listeners>
<listener class-name="listeners.listenerTestNG"/>
</listener>
<test name="Test">
<classes>
<classname="listeners.ListenerTestNGTestCase">
</classes>
</test>
</suite>
65
Execute it by right clicking on testng.xml and run as TestNG Suite
Case 1: Execute failed test cases using TestNG in Selenium – By using “testng-failed.xml”
Steps To follow:
1. After the first run of an automated test run. Right click on Project – Click on Refresh
2. A folder will be generated named “test-output” folder, Inside “test-output” folder, you could find “testng-
failed.xml”
3. Run “testng-failed.xml” to execute the failed test cases again.
Case 2: Execute failed test cases using TestNG in Selenium – By Implementing TestNG IRetryAnalyzer.
//This method will be called everytime a test fails. It will return TRUE if a test fails
// and need to be retried, else it returns FALSE
public boolean retry(ITestResult result) {
if (retryCnt < maxRetryCnt) {
System.out.println("Retrying " + result.getName() + " again and the count is " + (retryCnt+1));
retryCnt++;
return true;
}
return false;
}}
Let us see the example by executing simple tests below. Here I took two test cases say Test1 and Test2.
Testcase 1: Testcase 2:
public class Test1 { public class Test2 {
@Test @Test
public void test1(){ public void test2(){
System.out.println("Test 1"); System.out.println("Test 2");
Assert.assertTrue(true); Assert.assertTrue(false);
} } }
}
As per the lines of code in Test2, it will fail. So it (Test2) will be executed 2 times (we took the maxRetryCnt as
2) in Retry Class. First lets include below mentioned Listener to testng.xml file. Below mentioned syntax is to
add Listener for RetryListnereClass. Final testng.xml file should looks like below:
67
Execute the testng.xml. Here is the output which I got. You could see in the below mentioned result that the
Test 2 is executed three times as we have mentioned ‘maxRetryCnt = 2’. Even though we have just 2 tests, we
could find total test runs are 4 in the result.
============================
Everjobs Suite
Total tests run: 4, Failures: 1, Skips: 2
============================
This way we could run failed test cases using TestNG in Selenium.
Once we execute test cases using TestNG, it will generate a default HTML report. Open in ‘test-output’
folder. Now you should find a report ”emailable-report.html‘. This is the default report generated by TestNG.
Open emailable -report.html using any browser of your choice.
68
17. How To Run TestNG Using Command Prompt ?
Step ii. Keep all the library files in a folder (here I create a folder name “lib”)
69
Step v: Open command prompt
C:\Users\workspace\SoftwareTestingMaterial
set classpath=C:\workspace\SoftwareTestingMaterial\bin; C:\ workspace\SoftwareTestingMaterial\lib\*
java org.testng.TestNG C:\workspace\SoftwareTestingMaterial\testng.xml
Also you could run TestNG using Batch file (.bat file)
70
Copy the below code and place it in a notepad and save the file using .bat extension
set projectLocation =
C:\Users\Admin\Desktop\STMSeleniumTutorial\workspace\SoftwareTestingMaterial
cd %projectLocation%
set classpath=%projectLocation%\bin;%projectLocation%\lib\*
java org.testng.TestNG %projectLocation%\testng.xml
pause
71
18. TestNG Reporter Logs
We need the information which helps the User to understand the test steps or any failure during the test
case execution. With the help of TestNG Reporter Logs it is possible to enable logging during the Selenium test
case execution.
In selenium there are two types of logging. High level logging and Low level logging. In low level logging
we try to produce logs for the every step you take or every action you make in your automation script. In high
level logging you just try to capture main events of your test.
Here, perform low level logging with log4j and high level logging with Testng reporter logs.
1) Write a test case for Sign In application and implement Log4j logging on every step.
2) Insert Reporter logs on the main events of the test.
72
Run the Test Script Run as TestNG, and check following Log file will be generated in logs folder
Check the index.html file in output folder of TestNG, reporters log will look like this -
Log4j logging will help you to report a bug or steps taken during the test, on the other hand reporters log will
help you to share the test status with leadership. As leadership is just interested in the test results, not the test
steps.
We can use reporter’s logs on the verification during the test. For example
if(Text1.equals(Text2)){
}else{
73
Stale Element Ref Exception & No Such Element Exception (Notes By – Vaibhav Mhaskar)
Hierarchy :
NotFoundException
NoAlertPresentException NoSuchWindowException
NoSuchContextException NoSuchFrameException
NoSuchElementException
The NotFoundException is a super class which includes the subclass NoSuchElementException. The
known direct subclasses of NotFoundException are: NoAlertPresentException, NoSuchContextException,
NoSuchElementException, NoSuchFrameException and NoSuchWindowException.
1. The NoSuchElementException is thrown when the element you are trying to find a Element which is
not in the DOM. This can happen for three reasons.
A. When element does not exist and never will, To fix this, change your findElement to be correct.
B. When element does not exist until you will do some actions, means until you are not selecting a
country, list of metro cities of that specific country will not be visible on DOM.
C. The third is that the element is generated by javascript but WebDriver attempts to find the
element before the javascript has created it. The fix for this is to use WebDriverWait to wait for
the element to appear (visibility and / or clickable).
2. StaleElementReferenceException is when you find an element, the DOM gets modified then you
reference the WebElement. For example,
WebElement we = driver.findElement(By.cssSelector("#valid"));
// you do something which alters the page or a javascript event alters the page
we.click();
Sometimes this will throw a StaleElementReferenceException but sometimes the timing will be
different and the click will work. I've seen many people have this intermittent problem. They add more
code which doesn't fix the problem. The extra code just changes the timing and hides the problem. The
problem comes back a few days later. So they add more random code. It looks like they fixed the problem
but they just changed the timing. So if you get a StaleElementReferenceException and it is not clear why,
it is probably this problem and you need to figure out how to make the findElement and click atomic.
75
WebDriver Event Listener (Notes By – Vaibhav Mhaskar)
Listeners “listen” to the event defined in the selenium script and behave accordingly. The main purpose of using
listeners is to create logs and reports.
WebDriverEventListener :
This WebDriverEventListener interface allows us to implement the methods. While Test script is
executing, Selenium WebDriver performs activities such as Type, Click, Navigate etc., To keep track of these
activities we can use WebDriver Event Listeners interface.
EventFiringWebDriver :
This EventFiringWebDriver class actually fire WebDriver event. Lets see how to implement Listeners in
Selenium WebDriver Script.
Step 4: In the Class “ListenerMainClass“, Create an object of the Class “EventCapture” where we implemented all the
methods of WebDriverEventListener to register with EventFiringWebDriver.
Lets see, each step in detail to implement the WebDriver Event Listeners in Selenium:
76
Step 2: Create another Class “ListenerMainClass” and write a script (which ever script you prefer). Below script opens
two webpages one after other and navigates backs to the first webpage.
Step 3: In the Class “ListenerMainClass“, Create EventFiringWebDriver object and pass driver object as a parameter.
Step 4: In the
Class “ListenerMainClass“, Create an object of the Class “EventCapture” where we implemented all the methods
of WebDriverEventListener to register with EventFiringWebDriver.
Finally, execute the “ListenMainClass” class. Methods in class “EventCapture” are called automatically based on
the script. Verify the Output in the console. You could find the logs in the console. The two url’s in the console are just
because the implementation of beforeNavigateBack( ) and afterNavigateBack( ) methods.
In case of WebDriver, whenever anyone clicks on a button on a web page, then automatically a method will be called
actionPerformed() in ActionListener case.
But in case of TestNG, there are the actual "listeners" which listen (here the method gets called automatically)
to the test execution events. A few examples are: onStart(), beforeStart(), afterFinish(), and onFinish() etc. Mostly, the
TestNG automation teams implement their own custom listeners for custom Logging and reporting.
77
WebDriver listeners too do a similar job...of logging and/or reporting. But then both of them work on different event sets.
WebDriver works on different automation events whereas TestNG works on different test's related events. The point to
note is that, with WebDriver listeners, "Logging" happens before/after event occurance such as click/SendKeys etc.
“WebDriver Listeners are Action Event Level Listeners & TestNG Listener is Test Event Listener”
78
How to deal with Captcha ? (Notes By – Vaibhav Mhaskar)
We cannot automate Captcha as it is not meant to be automatized. Suppose we have to automate the test
case for the web page which having captcha, so in this scenario let’s see how to deal with Captcha.
Option 1 : Either ask development team for a workaround, like configure Captcha in test Environment in such
way it will always accept 1 specific value.
Option 3 : If you are using custom captcha module, you can ask developer to generate an API of captcha
generation for Testing environment.
Option 4 : You can ask to development team to add captcha code as title in markup then you can access this
title and bypass the captcha, but only in the testing environment.
Note : When you do work around for captcha in test environment , you should always have this point in your
checklist to make sure workarounds foe captcha testing are removed before it goes on production
79
MANTIS Bug Tracker Tutorial For Beginners (source – guru99) (Notes By – Vaibhav Mhaskar)
MANTIS is an open source bug tracking software. It can be used to track bug for various software projects. You can
easily download and install the Mantis for your use. Mantisbt now also provides a hosted version of the software. Some
salient features of Mantis Bt are as follows
Email notifications: It sends out emails of updates, comments, resolutions to the concerned stakeholders.
Access Control: You can control user access at a project level
Customize: You can easily customize Mantis as per your requirements.
Mobile Support: Mantis supports iPhone, Android, and Windows Phone Platforms.
Plugins: An ever-expanding library of plugins to add custom functionality to Mantis Issue Tracker.
Step 2) Once you login to Mantis your user-name will be displayed on the top of the Mantis main screen and now you can
report your issue into the Mantis by clicking on the option "Report Issue" as shown below.
80
Step 3) In the next Screen
81
NOTE: The fields you see in your version of Mantis will defer. Refer our section on Custom Fields for the same.
Step 4)After entering all the details in the report window, we will submit a report and soon our report will be displayed on
the main window. As show in the screen-shot below, when you click on view issue, the issue will appear on the screen with
the id "0017896" also, it shows the status as new and also the date when it was created.
The issues in the Mantis Tool are highlighted according to the status of an issue. For example here the issue is in
acknowledged status, therefore, highlighted in light orange.
Step 5) When you click on your issue #id 0017896, it will show the issue in more details like project reporter, its status,
date submitted and last updated.
82
Step 6) Apart from these, you can add a file, documents, images to your bug as shown below –
Step 7) You can also add comments addressing your issue as shown in the screen-shot below.
Step 8) You can click history at top of the Issue Report, to see issue history. This issue history has details like when the
issue was created, or when the file was added to the issue or if there is any note added to the issue.
83
Step 9) Once the issue is submitted the developer receives an email.
84
Step 2) Project is created.
Step 2)
1. Enter
2. Username
3. Real Name
4. Email
5. Access Level
6. Click Create User
85
Step 3) In the next screen assign user to the desired project.
86
Step 3) Login credentials are sent to the user on him email.
Step 1)
Step 2)
87
Step 3) Custom Field is created
Step 4) Click the Custom Field Again and Link Custom Field to your Project
Step 5) In the Report Issue section, the new custom field is reflected
88
Mantis Interview Question
1. Question 1. What Is Mantis Bug Tracker?
Answer :
MANTIS is a free, open source bug tracking software. It can be used to track bug for various software projects. You can
easily download and install the Mantis for your use. Mantis now also provides a hosted version of the software.
Email notifications: It sends out emails of updates, comments, resolutions to the concerned stake holders.
89
Customize: You can easily customize Mantis as per your requirements.
Mobile Support: Mantis supports iPhone, Android and Windows Phone Platforms.
New: In finding an issue in testing, all relevant checks are performed, like whether it was occurring in the previous
release. If the issue is so, reopening the bug and creating new defect is done by changing the status of that defect to
‘new’.
Open: When a new bug is opened, development or project manager revises it, followed by assigning the task to the
developer, and changes the status from ‘new’ to ‘open’.
When the bug is found by the tester, the status is marked as NEW. Once this bug is verified by the test lead for its
validity, the status is changed to OPEN.
Show-stopper / critical bugs: The core dumps, products abnormally shuts down and no work around will be found out,
like OS automatic freezing.
Major Bugs: The work around is found, but the implementation cant be done, like performance degradency.
Medium Bugs: These bugs include database errors, link errors, low response time
90
o Never assume anything while tracking a bug.
Title should be clear: A good title is a must, which the essence of the bug report be well grasped by the developer.
One Report per Bug : A bug report should have only one bug and not more or no less. In case more bugs are placed,
some of the bugs may be overlooked.
Minimum steps to reproduce the Bug: This is a very important tip. Developers need to get the problem in the shortest
possible time. So the tester needs to help them for doing just that task. Testers need to have few rounds of testing and be
able to produce the problems using minimum steps.
Expected and observed results: A bug report should always contain the expected and the observed result. Testers
should take the responsibility to explain the developers that what went wrong.
The build that the problem occurs: It is common in the daily builds. If the exact problematic build is not specified by
the tester, it is hard for developers to resolve an already-solved problem.
Pictures: ‘A picture is worth a thousand words’! it is better to have a clear picture that perfectly illustrates the problem.
o A bug is getting a problem at the time of testing, where as a defect is problem that got by the customer in
production time
o A bug is a fault in a program which causes it to behave abruptly. Bugs are usually found either during
unit testing done by developer of module testing by testers.
o A defect is found when the application does not conform to the requirement specification. A defect can
also be found when the client or user is testing.
91
8. Question 8. What Is The Process Of Bug Cycle?
Answer :
Bug retesting:when the developer fixes the bug and given to the tester
Bug closing and reopening:when the tester retested and the status is changed to ‘closed’.
10. Question 10. How To View Specific Projects In Mantis Bug Tracker?
Answer :
o Log in with your username and password. If you’ve forgotten your credentials, you can reset your
password using your email address from the link on the login page.
o To see your project’s main page, you must select its name in the drop-down menu displayed in the upper
right corner of the screen. Once the page loads, click on the tab 'See issues' to see all the previous entry
bugs for this project.
11. Question 11. Explain How To Report A Bug In Mantis Bug Tracker?
Answer :
1) To report a new issue, click on 'Report Issue' in the main menu bar (shown below.)
92
2) A form will open titled “Enter Report Details”. You must fill in every field that it contains. The following steps
describe how to do this
3) First, you must always select 'All projects – general' in the *Category drop-down menu.
4) Select the reproducibility from the second dropdown. Keep in mind that as much as you can, you should find the
bug’s circumstances before logging it. Ideally, you should be able to reproduce it 100%. But sometimes it is impossible.
In these rare cases, you can use 'sometimes' if the bug occurs randomly if you really are unable to reproduce it.
Minor if the bug is important but not harmful to the core functioning of a feature
Critical if the bug completely prevents the user from continuing what he was doing. if the bug crashes site or application
'Low' if the bug has very little impact on the user’s experience
9) In the summary field, enter a title for your bug. The title should begin with the name of the section of the
app/website/game in which the bug happens between brackets [], followed by a brief description of the bug.
10) Update the description field the detailed info about the bug.
11) The 'Steps to reproduce' section should contain the steps that a developer or other tester should follow to reproduce
the issue
12) The 'Additional information' field must be used to inform the developer of what device/browser and on what
device/browser version the bug was found
14) View status should be left public and the ‘report stay’ checkbox should be left unchecked unless you have another
issue to enter immediately.
93
12. Question 12. Does Mantis Provide An Xml-rpc Interface?
Answer :
13. Question 13. Is There A Mantis Version For Smart Phones / Pdas?
Answer :
Yes, MantisWAP provides a very light weight interface for Mantis access through a smart phone or PDA. It is optimize
for speed and minimization of consumed bandwidth.
Go to Manage > Manage Users and Click on 'Create New Account' and update below fields:
o Username
o Real Name
o Email
o Access Level
o Click Create User
In the next screen assign user to the desired project.Update Email and other Account Preferences as desired. After that
the login credentials are sent to the user on their email.
94
o Enter Field Name
o Click Button 'New Custom Field'
o Select Field Type
o Enter Field Specific Data
o Hit Update Custom Field
Now the custom field got created. Click the Custom Field Again and Link Custom Field to your Project. After that in
Report Issue section, the new custom field will be reflected.
17. Question 17. Does Mantisbt Integrate With Source Control Tools?
Answer :
Scmbug is a system that integrates software configuration management (SCM) with bug-tracking. It aims to be a
universal tool that will glue any source code version control system (such as CVS, Subversion, and Arch) with any bug-
tracking system (such as Bugzilla, MantisBT, and Request Tracker).
o Use MantisBT Forums or mantisbt-help at lists dot sourceforge dot net for posting questions. Our
preference goes to the forums.
o Use mantisbt-dev at lists dot sourceforge dot net for development related discussions.
o Use Mantis Bug Tracker for reporting feature requests and bugs.
o Use MantisBT Manual comments to identify a problem with the documentation or to contribute hints that
are ought to be part of the documentation.
o Use mantisbt-lang at lists dot sourceforge dot net for discussions relating to localisation to a specific
language.
o If you are about to implement a major feature, it is strongly recommended to get in touch with the
developers. Such interaction will make it much more likely that your mods be applied to MantisBT
distribution.
o Patches should be attached to a Mantis Bug Tracker issue.
o A patch should be attached as a single zip or .tar.gz file.
o A patch should include a copy of all new files / modified files as well as a diff (patch) file (if possible).
95
o A patch should only contain one feature. If a patch has a mixed bag of features, it makes it harder to
understand and apply.
o If you require feedback from developers relating to the patch, then post a message to mantisbt-dev at lists
dot sourceforge dot net which refers to the issue including your patch. Ideally, the feedback will be added
to the issue as notes. If not, then the patch owner should summarise the feedback as notes.
o Fixes and updates to the patch should be attached to the same issue as should be marked clearly. With
every attachment there should be a note that refers to the file name and specifies the updates done.
o Join MantisBT IRC channel for realtime discussions with developers.
o Patches should following MantisBT coding style.
o Keep your patches up-to-date as new MantisBT versions are released.
96
Eclipse Plug-in for GIT and GIT-Hub (Notes By – Vaibhav Mhaskar)
The process of sending Code from eclipse to GIT local repository daily is called as Commit.
And The process of sending Code from GIT local repository to remote GIT HUB repository is called as
Push.(check out)
The process of extracting Code from remote GIT HUB repository to GIT local repository to is called as Pull.
(check in)
The process of extracting Code from GIT local repository to eclipse to daily is called as Request .
Need to install GIT plug in eclipse thro market place Search GIT and install EGIT integration with eclipse
search option (Quick Access GIT Repositories) Clone a GIT repository provide URL
Step 2. Commit and Push your Project to GIT & GIT Hub
(Only 1st Time) Select your project right click team share project select GIT repository from drop
down finish
(from 2nd time and every time whenever to do changes) Select your project right click team commit
(wen u modifies the code)
Select your project right click team commit ---- select your all files from unstaged changes
box – drag n drop them to changed stages click on commit and push
97
GIT Installation, download GIT from following link
http://git-scm.com/download/win/
98
Window 1.--- Run the setup file..
99
Window 2.--- Click on Next button
100
Window 4. -- Check the box for Git Bash Here and Git GUI Here and click Next…
101
Window 6. --- Click on Next >
Window 7.-- Select Use GIT From Git Bash only and click Next >
102
Window 8. -- Select Use the OpenSSL library and click Next >
Window 9. Select Checkout Windows-Style, commit Unix-style line endings and click Next >
103
Window 10. select Use MinTTY (the default terminal of MSYS2 ) and click Next>
Window 11 Select Enable file system caching and Enable Git Credential Manager click Install
104
Window 12. installing window
105
Now follow following steps to create GitHub Repository and Git Local Repository
1. Sign up on https://github.com/
2. Create your account and create new repository by clicking on Start Project
Create a Folder on your Computer as a Git Local Repository and name it as per your convenience
2. after entering local repository right click and click on Git Bash Here. Window like command prompt
will appear as follows
4. As soon as you execute above command, empty folder/Directory will become Git Local repository. See
following window.
106
e.g. $ git remote add origin “--------url---------”
Actions -
Our GitHub remote repository having README file. Refer above picture. We have to pull that file to our local
Repository Git.
107
This pic is of SDET videos
pic not practice pic
2. If number of files are present in a folder It doesn’t mean that, that all files are part of Git repository
(local repository). May be some files are part of Git and some files are not. Then how to check this
status of local repository i.e. Git. Use following command ..
Above pics shows, text.properties is file present in a folder but not part of Git
i.e. $ git add text.properties press enter (to add specific file to index)
108
$ git add -a press enter (to add all unadded files to index)
Note : files which are added to index are ready to add in Git Repository (local)
( the file text.properties is get added to Git Repository we can check status)
After addition of files to repository folder and modification of already added file it is necessary
to add that files to index first then it will be ready to add into Git local Repository by “ $ git commit
(file name) ”.
$ git log presss enter (this will show you actions log)
(the files of local Git Repo will be added to remote GitHub termed that GitHub Repo files are
unchanged , unmodified and same as it was means no new files are added to GitHub. If not then first we
have to pull that file first then we can push tp Git Hub)
109
Over View of Commands
110
111
112
113
Git Commands (Notes By – Vaibhav Mhaskar)
114
Basic Manual Testing (Notes By – Vaibhav Mhaskar)
Manual Testing is a process of finding out the defects or bugs in a software program. In this method the tester
plays an important role of end user and verifies that all the features of the application are working correctly. The
tester manually executes test cases without using any automation tools.
The tester prepares a test plan document which describes the detailed and systematic approach to testing
of software applications. Test cases are planned to cover almost 100% of the software application. As manual
testing involves complete test cases it is a time consuming test.
The differences between actual and desired results are treated as defects. The defects are then fixed by the
developer of software application. The tester retests the defects to ensure that defects are fixed. The goal of
Manual testing is to ensure that application is defect & error free and is working fine to provide good quality work
to customers.
Smoke Testing
Smoke Testing is a kind of Software Testing performed after software build to ascertain that the critical
functionalities of the program is working fine. It is executed "before" any detailed functional or regression tests
are executed on the software build. The purpose is to reject a badly broken application, so that the QA team does
not waste time installing and testing the software application.
In Smoke Testing, the test cases chosen cover the most important functionality or component of the
system. The objective is not to perform exhaustive testing, but to verify that the critical functionalities of the
system is working fine. For Example a typical smoke test would be - Verify that the application launches
successfully, Check that the GUI is responsive ... etc.
Sanity Testing
Sanity testing is a kind of Software Testing performed after receiving a software build, with minor changes
in code, or functionality, to find that the bugs have been fixed and no further issues are introduced due to these
changes. The goal is to determine that the proposed functionality works roughly as expected. If sanity test fails,
the build is rejected to save the time and costs involved in a more rigorous testing.
The objective is "not" to verify thoroughly the new functionality, but to determine that the developer has
applied some rationality (sanity) while producing the software.
115
For instance, if your scientific calculator gives the result of 2 + 2 =5! Then, there is no point testing the
advanced functionalities like sin 30 + cos 50.
Regression Testing
Regression Testing is testing to confirm that a recent program or code change has not adversely affected
existing features. Regression Testing is nothing but full or partial selection of already executed test cases which
are re-executed to ensure existing functionalities work fine.
This testing is done to make sure that new code changes should not have side effects on the existing
functionalities. It ensures that old code still works.
Functional Testing
1. Adhoc Testing
2. Exploratory Testing
3. Globalization Testing
4. Integration Testing
116
STLC (Software Testing Life cycle)
STLC stands for Software Testing Life Cycle. STLC is a sequence of different activities performed by the testing
team to ensure the quality of the software or the product.
STLC is an integral part of Software Development Life Cycle (SDLC). But, STLC deals only with the
testing phases.
STLC starts as soon as requirements are defined or SRD (Software Requirement Document) is shared by
stakeholders.
In the early stage of STLC, while the software or the product is developing, the tester can analyze and
define the scope of testing, entry and exit criteria and also the Test Cases. It helps to reduce the test cycle
time along with better quality.
As soon as the development phase is over, the testers are ready with test cases and start with execution.
This helps to find bugs in the initial phase.
STLC Phases
STLC has the following different phases but it is not mandatory to follow all phases. Phases are dependent
on the nature of the software or the product, time and resources allocated for the testing and the model of SDLC
that is to be followed.
STLC Diagram -
Requirement Analysis − When the SRD is ready and shared with the stakeholders, the testing team starts
high level analysis concerning the AUT (Application under Test).
Test Case Designing − Develop the test cases based on scope and criteria’s.
117
Test Environment Setup − When integrated environment is ready to validate the product.
Description -
New - If Bug found to a tester then it is assigned to a Developer team usually assignment task done by teamlead to Dev
Team
1) Assigned - The assigned Bug is checked by Dev Team for its correctness (Wheather it is a Bug or not)
Deferred – If it is a Bug, but not a Major bug or It may solved later on in a next sprint then it is deferred. Bug
Status is deferred.
Duplicated – If the assigned bug is already logged by someone then on reassignment of that bug it is made as
a Duplicated.
Reopen – After Fixation of a bug it is reopened by Tester Team to check its proper Fixation
4) Retest - Fixed Bug is Retested to check wheather Bug is still exists or not. If the bug still exists then it is reassigned to
Dev Team.
5) Close – After retesting the fixed bug not found again, means it is fixed properly then it is closed.
118
119
120
Log4j (Notes By – Vaibhav Mhaskar)
Every application in software industry maintains some log file. If you find any bug then we have to provide a steps,
screenshots. Some times steps and screenshot are not enough to analyze the issue in that case Develpoment people will
ask for log files.
Log4j Features
It is thread-safe.
It is optimized for speed.
It is based on a named logger hierarchy.
It supports multiple output appenders per logger.
It supports internationalization.
It is not restricted to a predefined set of facilities.
Logging behavior can be set at runtime using a configuration file.
It is designed to handle Java Exceptions from the start.
It uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
The format of the log output can be easily changed by extending the Layout class.
The target of the log output as well as the writing strategy can be altered by implementations of the Appender
interface.
It is fail-stop. However, although it certainly strives to ensure delivery, log4j does not guarantee that each log
statement will be delivered to its destination.
1. All - This level of logging will log everything ( it turns all the logs on )
2. DEBUG - print the debugging information and is helpful in development stage
3. INFO - print informational message that highlights the progress of the application
4. WARN - print information regarding faulty and unexpected system behavior.
5. ERROR - print error message that might allow system to continue
6. FATAL - print system critical information which are causing the application to crash
7. OFF - No logging
121
Configuring log4j involves assigning the Level, defining Appender, and specifying Layout objects in a
configuration file. Add Log4j jar dependencies to your Maven project. These jar file are provided by Apache POI. We have
to add either Log4j.xml file or Log4j.properties only to your project. We are adding Log4j.properties file to our demo
project.
To configure log4j we have to decide which appender to implement. Accordingly, parameters of appender will
be set.
log4j.rootLogger=debug,file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=F:\Java Basic\log4j\Logs\Selenium.logs
log4j.appender.file.maxfileSize=5000KB
log4j.appender.file.maxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.conversionPattern=%d{ABSOLUTE} %5p %c<strong>{}</strong>:%L - %m%n
log4j.appender.file.Append=false
#Application Logs
log4j.logger.devpinoyLogger=DEBUG,dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxfileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1conversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=F:\Java Basic\log4j\Logs\Manual.logs
log4j.appender.dest1.Append=false
In the above Example, we have configured log4j to log in two different files named as Selenium.log and Manual.log.
file and dest1 are the two identifiers.
"File" is used to give file name in which logs will be saved
"maxFileSize" is used to configure the maximum size of the log file. When file reaches this size, a new file will
be created with the same name and the old file name will be add as an Index to it.
"maxBackupIndex" is used to configure maximum number of files to be backup.
"layout" is used to set the format of the log file.
"Append" is used to set append function. If it is set to false, than every time a new file will be created rather than
old file will be used for logging
122
Example Code –
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator; // when using log4j.xml file
// import org.apache.log4j.PropertyConfigurator; // when using log4j.properties file
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
123
How To Explain Selenium Framework (Notes By – Vaibhav Mhaskar)
Packages –
124
Description
125
Dynamic WebTable Handling (Notes By – Vaibhav Mhaskar)
There are two types of Web Table- Static web Table and Dynamic WebTable. The Table whose content are not
changing is a Static WebTables and the table whose contents are changing frequently after some time duration is the
Dynamic WebTable.
<tabel>
<tbody>
<tr>
<td> Sr.No </td>
<td> Student Name </td>
<td> Roll Number </td>
</tr>
<tr>
<td id=”firstStudent”>001</td >
<td>Avinash</td >
<td>A100</td >
</tr>
</tbody>
</table>
1st Row of
WebTable
2nd Row of
WebTable
127
(Above code did by Avi sir… search on youtube)
128
Software/ plugin / jars Versions (Notes By – Vaibhav Mhaskar)
129
Maven Interview Questions (Notes By – Vaibhav Mhaskar)
1) What is Maven?
Maven is a project management tool. It is based on POM (Project Object Model).
Ant Maven
It is a tool box It is Framework
It is mainly a build tool It is project Management toll
There is no life cycle. There is a life cycle.
Ant doesn't have formal conventions. Maven has a convention to place source code, compiled code etc.
Ant is procedural. Maven is declarative.
The ant scripts are not reusable. The Maven plugins are reusable.
13) Give the command for installation of the JAR file in a local repository.
mvn install
131
POM stands for Project Object Model. The pom.xml file contains information of project and project
configuration.
28) What is Maven Archetypes? And what are the Project Types?
Archetypes are templates to create a variety of Java project structures, including web applications specific to a
container such as Wildfly. In other words, it is a tool that creates the stuff you build the project on top of.
Project Types:
1. War
2. Jar
3. Ear
132
4. Wildfly
5. JMS
6. Android
project dependencies
plugins
goals
build profiles
project version
developers
mailing list
37) What is Maven Build Lifecycle?
A Build Lifecycle is a well defined sequence of phases which define the order in which the goals are to be
executed. Here phase represents a stage in life cycle.
134
38 ) Name the 3 build lifecycle of Maven.
The three build lifecycles are −
SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven
checks for a new SNAPSHOT version in a remote repository for every build.
43) How Maven handles and determines what version of dependency will be used when multiple version
of an artifact are encountered?
Maven determines what version of a dependency is to be used when multiple versions of an artifact are
encountered. If two dependency versions are at the same depth in the dependency tree, the first declared
dependency will be used. This is called dependency mediation.
A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a
distribution of one or more related mojos.
<groupId>:<artifactId>:<version>
135
Tell me About Your Self
Hi xxxxxx,
I am XXXXXXXX , having N.N years of experience as a Q. A. Automation Tester. I am working with XXXX
from Jan/Feb/March 20XX.
I am experienced in (Domain Name )- Health Care and E-Commerce domain. I have worked on Selenium
WebDriver in Eclipse IDE, Hybrid Driven Framework, TestNG
My responsibilities are –
1. writing a Automation Testing Scripts using Java and selenium
2. maintaining Automation framework which is Hybrid using POM
3. Maintaing logs using Log4j
4. Defect logging
5. Generating customized report using Extent Report
6. Understanding the BRS (Business Requirment Specification)
7. Attending Daily Scrum Meeting
8. Documentation
9. Involved in maintenance of Automation Framework
10. Developing scripts to read / write data from database
I am Engineering Graduated /Post Graduated in XXXX stream and currently living in Pune/XXXXXX
I am enthusiastic and dedicated to my work and looking for wonderful career in Automation Testing
(For this type of question you are supposed to explain your roles and responsibilities, duties, Key skills)
136