Selenium
Ques.1.
What is Selenium?
What is Selenium?
Ans. Selenium is a robust
test automation suite that is used for automating web based applications. It
supports multiple browsers, programming languages and platforms.
test automation suite that is used for automating web based applications. It
supports multiple browsers, programming languages and platforms.
Ques.2.
What are different forms of selenium?
What are different forms of selenium?
Ans. Selenium comes in four
forms-
forms-
Selenium WebDriver –
Selenium WebDriver is used to automate web applications using browser’s native
methods.
Selenium WebDriver is used to automate web applications using browser’s native
methods.
Selenium IDE – A firefox
plugin that works on record and play back principle.
plugin that works on record and play back principle.
Selenium RC – Selenium
Remote Control(RC) is officially deprecated by selenium and it used to work on
javascript to automate the web applications.
Remote Control(RC) is officially deprecated by selenium and it used to work on
javascript to automate the web applications.
Selenium Grid – Allows
selenium tests to run in parallel across multiple machines.
selenium tests to run in parallel across multiple machines.
Ques.3.
What are some advantages of selenium?
What are some advantages of selenium?
Ans. Following are the
advantages of selenium-
advantages of selenium-
Selenium is open source and
free to use without any licensing cost.
free to use without any licensing cost.
It supports multiple languages
like Java, ruby, python etc.
like Java, ruby, python etc.
It supports multi browser
testing.
testing.
It has good amount of
resources and helping community over the internet.
resources and helping community over the internet.
Using selenium IDE
component, non-programmers can also write automation scripts
component, non-programmers can also write automation scripts
Using selenium grid
component, distributed testing can be carried out on remote machines possible.
component, distributed testing can be carried out on remote machines possible.
Ques.4.
What are some limitations of selenium?
What are some limitations of selenium?
Ans. Following are the
limitations of selenium-
limitations of selenium-
We cannot test desktop
application using selenium.
application using selenium.
We cannot test web services
using selenium
using selenium
For creating robust scripts
in selenium webdriver, programming langauge knowledge is required.
in selenium webdriver, programming langauge knowledge is required.
Ques.5.
Which all browsers/drivers are supported by Selenium Webdriver?
Which all browsers/drivers are supported by Selenium Webdriver?
Ans. Some commonly used
browsers supported by selenium are-
browsers supported by selenium are-
Google Chrome – ChromeDriver
Firefox – FireFoxDriver
Internet Explorer –
InternetExplorerDriver
InternetExplorerDriver
Safari – SafariDriver
HtmlUnit (Headless browser) –
HtmlUnitDriver
HtmlUnitDriver
Android – Selendroid/Appium
IOS – ios-driver/Appium
Ques.6.
Can we test APIs or web services using Selenium webdriver?
Can we test APIs or web services using Selenium webdriver?
Ans. No selenium webdriver
uses browser’s native method to automate the web applications. Since web
services are headless, so we cannot automate web services using selenium
webdriver.
uses browser’s native method to automate the web applications. Since web
services are headless, so we cannot automate web services using selenium
webdriver.
Ques.7.
What are the testing type supported by Selenium WebDriver?
What are the testing type supported by Selenium WebDriver?
Ans. Selenium webdriver can
be used for performing automated functional and regression testing.
be used for performing automated functional and regression testing.
Ques.8.
What are various ways of locating an element in selenium?
What are various ways of locating an element in selenium?
Ans. The different locators
in selenium are-
in selenium are-
Id
XPath
cssSelector
className
tagName
name
linkText
partialLinkText
Ques.9.
What is an XPath?
What is an XPath?
Ans. Xpath or XML path is a
query language for selecting nodes from XML documents. XPath is one of the
locators supported by selenium webdriver.
query language for selecting nodes from XML documents. XPath is one of the
locators supported by selenium webdriver.
Ques.10.
What is an absolute XPath?
What is an absolute XPath?
Ans. An absolute XPath is a
way of locating an element using an XML expression beginning from root node
i.e. html node in case of web pages. The main disadvantage of absolute xpath is
that even with slightest change in the UI or any element the whole absolute
XPath fails.
way of locating an element using an XML expression beginning from root node
i.e. html node in case of web pages. The main disadvantage of absolute xpath is
that even with slightest change in the UI or any element the whole absolute
XPath fails.
Example – html/body/div/div[2]/div/div/div/div[1]/div/input
Ques.11.
What is a relative XPath?
What is a relative XPath?
Ans. A relative XPath is a
way of locating an element using an XML expression beginning from anywhere in
the HTML document. There are different ways of creating relative XPaths which
are used for creating robust XPaths (unaffected by changes in other UI
elements).
way of locating an element using an XML expression beginning from anywhere in
the HTML document. There are different ways of creating relative XPaths which
are used for creating robust XPaths (unaffected by changes in other UI
elements).
Example – //input[@id=’username’]
Ques.12.
What is the difference between single slash(/) and double slash(//) in XPath?
What is the difference between single slash(/) and double slash(//) in XPath?
Ans. In XPath a single slash
is used for creating XPaths with absolute paths beginning from root node.
is used for creating XPaths with absolute paths beginning from root node.
Whereas double slash is used
for creating relative XPaths.
for creating relative XPaths.
Ques.13.
How can we inspect the web element attributes in order to use them in different
locators?
How can we inspect the web element attributes in order to use them in different
locators?
Ans. Using Firebug or
developer tools we can inspect the specific web elements.
developer tools we can inspect the specific web elements.
Firebug is a plugin of
firefox that provides various development tools for debugging applications.
From automation perspective, firebug is used specifically for inspecting
web-elements in order to use their attributes like id, class, name etc. in
different locators.
firefox that provides various development tools for debugging applications.
From automation perspective, firebug is used specifically for inspecting
web-elements in order to use their attributes like id, class, name etc. in
different locators.
Ques.14.
How can we locate an element by only partially matching its attributes value in
Xpath?
How can we locate an element by only partially matching its attributes value in
Xpath?
Ans. Using contains() method
we can locate an element by partially matching its attribute’s value. This is
particularly helpful in the scenarios where the attributes have dynamic values
with certain constant part.
we can locate an element by partially matching its attribute’s value. This is
particularly helpful in the scenarios where the attributes have dynamic values
with certain constant part.
xPath expression = //*[contains(@name,’user’)]
The above statement will
match the all the values of name attribute containing the word ‘user’ in them.
match the all the values of name attribute containing the word ‘user’ in them.
Ques.15.
How can we locate elements using their text in XPath?
How can we locate elements using their text in XPath?
Ans. Using the text() method
–
–
xPathExpression = //*[text()=’username’]
Ques.16.
How can we move to parent of an element using XPath?
How can we move to parent of an element using XPath?
Ans. Using ‘..’ expression
in XPath we can move to parent of an element e.g. the locator //div[@id=”childId”]/.. will move to the
parent of the div element with id value as ‘childId’.
in XPath we can move to parent of an element e.g. the locator //div[@id=”childId”]/.. will move to the
parent of the div element with id value as ‘childId’.
Ques.17.
How can we move to nth child element using XPath?
How can we move to nth child element using XPath?
Ans. There are two ways of
navigating to the nth element using XPath-
navigating to the nth element using XPath-
Using square brackets with
index position-
index position-
Example – div[2] will find
the second div element.
the second div element.
Using position()-
Example – div[position()=3]
will find the third div element.
will find the third div element.
Ques.18.
What is the syntax of finding elements by class using CSS Selector?
What is the syntax of finding elements by class using CSS Selector?
Ans. By .className we can
select all the element belonging to a particluar class e.g. ‘.red’ will select
all elements having class ‘red’.
select all the element belonging to a particluar class e.g. ‘.red’ will select
all elements having class ‘red’.
Ques.19.
What is the syntax of finding elements by id using CSS Selector?
What is the syntax of finding elements by id using CSS Selector?
Ans. By #idValue we can select all the element belonging to a
particluar class e.g. ‘#userId’ will select the
element having id – userId.
particluar class e.g. ‘#userId’ will select the
element having id – userId.
Ques.20.
How can we select elements by their attribute value using CSS Selector?
How can we select elements by their attribute value using CSS Selector?
Ans. Using [attribute=value]
we can select all the element belonging to a particluar class e.g.
‘[type=small]’ will select the element having attribute type of value ‘small’.
we can select all the element belonging to a particluar class e.g.
‘[type=small]’ will select the element having attribute type of value ‘small’.
Ques.21.
How can we move to nth child element using css selector?
How can we move to nth child element using css selector?
Ans. Using :nth-child(n) we
can move to the nth child element e.g. div:nth-child(2) will locate 2nd div
element of its parent.
can move to the nth child element e.g. div:nth-child(2) will locate 2nd div
element of its parent.
Ques.22.
What is fundamental difference between XPath and css selector?
What is fundamental difference between XPath and css selector?
Ans. The fundamental
difference between XPath and css selector is using XPaths we can traverse up in
the document i.e. we can move to parent elements. Whereas using CSS selector we
can only move downwards in the document.
difference between XPath and css selector is using XPaths we can traverse up in
the document i.e. we can move to parent elements. Whereas using CSS selector we
can only move downwards in the document.
Ques.23.
How can we launch different browsers in selenium webdriver?
How can we launch different browsers in selenium webdriver?
Ans. By creating an instance
of driver of a particular browser-
of driver of a particular browser-
WebDriver driver =
new FirefoxDriver();
new FirefoxDriver();
Ques.24.
What is the use of driver.get(“URL”) and
driver.navigate().to(“URL”) command? Is there any difference between
the two?
What is the use of driver.get(“URL”) and
driver.navigate().to(“URL”) command? Is there any difference between
the two?
Ans. Both driver.get(“URL”) and driver.navigate().to(“URL”) commands are
used to navigate to a URL passed as parameter.
used to navigate to a URL passed as parameter.
There is no difference
between the two commands.
between the two commands.
Ques.25.
How can we type text in a textbox element using selenium?
How can we type text in a textbox element using selenium?
Ans. Using sendKeys() method we can type text in a textbox-
WebElement
searchTextBox = driver.findElement(By.id(“search”));
searchTextBox = driver.findElement(By.id(“search”));
searchTextBox.sendKeys(“searchTerm”);
Ques.26.
How can we clear a text written in a textbox?
How can we clear a text written in a textbox?
Ans. Using clear() method we can delete the text written in a
textbox.
textbox.
driver.findElement(By.id(“elementLocator”)).clear();
Ques.27.
How to check a checkBox in selenium?
How to check a checkBox in selenium?
Ans. The same click() method used for clicking buttons or radio
buttons can be used for checking checkbox as well.
buttons can be used for checking checkbox as well.
Ques.28.
How can we submit a form in selenium?
How can we submit a form in selenium?
Ans. Using submit() method we can submit a form in selenium.
driver.findElement(By.id(“form1”)).submit();
Also, the click() method can be used for the same purpose.
Ques.29.
Explain the difference between close and quit command.
Explain the difference between close and quit command.
Ans. driver.close() – Used to close the current browser having focus driver.quit() – Used to close all the browser
instances
instances
Ques.30.
How to switch between multiple windows in selenium?
How to switch between multiple windows in selenium?
Ans.Selenium has driver.get
WindowHandles() and
WindowHandles() and
driver.switchTo().window(“{windowHandleName}”)
commands
to work with multiple
commands
to work with multiple
windows. The getWindowHandles() command returns a list of ids
corresponding to each
corresponding to each
window and on passing a
particular window handle to
particular window handle to
driver.switchTo().window(“{windowHandleName}”)
command
we can switch
command
we can switch
control/focus to that
particular window.
particular window.
for (String
windowHandle : driver.getWindowHandles()) {
windowHandle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
Ques.31.
What is the difference between driver.getWindowHandle() and driver.getWindowHandles()
in selenium?
What is the difference between driver.getWindowHandle() and driver.getWindowHandles()
in selenium?
Ans.
driver.getWindowHandle() returns a handle of the current page (a unique
identifier)
driver.getWindowHandle() returns a handle of the current page (a unique
identifier)
Whereas driver.getWindowHandles() returns a set of handles of
the all the pages available.
the all the pages available.
Ques.32.
How can we move to a particular frame in selenium?
How can we move to a particular frame in selenium?
Ans. The driver.switchTo() commands can be used for switching
to frames.
to frames.
driver.switchTo().frame(“{frameIndex/frameId/frameName}”);
For locating a frame we can
either use the index (starting from 0), its name or Id.
either use the index (starting from 0), its name or Id.
Ques.33.
Can we move back and forward in browser using selenium?
Can we move back and forward in browser using selenium?
Ans. Yes, using
driver.navigate().back() and driver.navigate().forward() commands we can move
backward and forward in a browser.
driver.navigate().back() and driver.navigate().forward() commands we can move
backward and forward in a browser.
Ques.34.
Is there a way to refresh browser using selenium?
Is there a way to refresh browser using selenium?
Ans. There a multiple ways
to refresh a page in selenium-
to refresh a page in selenium-
Using driver.navigate().refresh() command
Using
sendKeys(Keys.F5) on any textbox on the webpage
sendKeys(Keys.F5) on any textbox on the webpage
Using driver.get(“URL”) on the current URL or
using driver.getCurrentUrl()
using driver.getCurrentUrl()
Using driver.navigate().to(“URL”)
on the current URL or
on the current URL or
driver.navigate().to(driver.getCurrentUrl());
Ques.35.
How can we maximize browser window in selenium?
How can we maximize browser window in selenium?
Ans. We can maximize browser
window in selenium using following command-
window in selenium using following command-
driver.manage().window().maximize();
Ques.36.
How can we fetch a text written over an element?
How can we fetch a text written over an element?
Ans. Using getText() method we can fetch the text over an
element.
element.
String text =
driver.findElement(“elementLocator”).getText();
driver.findElement(“elementLocator”).getText();
Ques.37.
How can we find the value of different attributes like name, class, value of an
element?
How can we find the value of different attributes like name, class, value of an
element?
Ans. Using getAttribute(“{attributeName}”) method we
can find the value of different attrbutes of an element e.g.-
can find the value of different attrbutes of an element e.g.-
String
valueAttribute = driver.findElement(By.id(“elementLocator”)).getAttribute(“value”);
valueAttribute = driver.findElement(By.id(“elementLocator”)).getAttribute(“value”);
Ques.38.
How to delete cookies in selenium?
How to delete cookies in selenium?
Ans. Using deleteAllCookies() method- driver.manage().deleteAllCookies();
Ques.39.
What is an implicit wait in selenium?
What is an implicit wait in selenium?
Ans. An implicit wait is a
type of wait which waits for a specified time while locating an element before
throwing NoSuchElementException. By default selenium tries to find elements
immediately when required without any wait. So, it is good to use implicit
wait. This wait is applied to all the elements of the current driver instance.
type of wait which waits for a specified time while locating an element before
throwing NoSuchElementException. By default selenium tries to find elements
immediately when required without any wait. So, it is good to use implicit
wait. This wait is applied to all the elements of the current driver instance.
driver.manage().timeouts().implicitlyWait(5,
TimeUnit.SECONDS);
TimeUnit.SECONDS);
Ques.40.
What is an explicit wait in selenium?
What is an explicit wait in selenium?
Ans. An explicit wait is a
type of wait which is applied to a particular web element untill the expected
condition specified is met.
type of wait which is applied to a particular web element untill the expected
condition specified is met.
WebDriverWait wait
= new WebDriverWait(driver, 10);
= new WebDriverWait(driver, 10);
WebElement element =
wait.until(ExpectedConditions.elementToBeClickable(By.id(“elementId”)));
wait.until(ExpectedConditions.elementToBeClickable(By.id(“elementId”)));
Ques.41.
What are some expected conditions that can be used in Explicit waits?
What are some expected conditions that can be used in Explicit waits?
Ans. Some of the commonly
used expected conditions of an element that can be used with expicit waits are-
used expected conditions of an element that can be used with expicit waits are-
elementToBeClickable(WebElement
element or By locator)
element or By locator)
stalenessOf(WebElement
element)
element)
visibilityOf(WebElement
element)
element)
visibilityOfElementLocated(By
locator)
locator)
invisibilityOfElementLocated(By
locator)
locator)
attributeContains(WebElement
element, String attribute, String value)
element, String attribute, String value)
alertIsPresent()
titleContains(String title)
titleIs(String title)
textToBePresentInElementLocated(By,
String)
String)
Ques.42.
What is fluent wait in selenium?
What is fluent wait in selenium?
Ans. A fluent wait is a type
of wait in which we can also specify polling interval(intervals after which
driver will try to find the element) along with the maximum timeout value.
of wait in which we can also specify polling interval(intervals after which
driver will try to find the element) along with the maximum timeout value.
Wait wait = new
FluentWait(driver)
FluentWait(driver)
withTimeout(20, SECONDS)
pollingEvery(5, SECONDS)
ignoring(NoSuchElementException.class);
WebElement textBox =
wait.until(new Function<webdriver,webElement>() {
wait.until(new Function<webdriver,webElement>() {
public WebElement
apply(WebDriver driver) {
apply(WebDriver driver) {
return driver.findElement(By.id(“textBoxId”));
}
}
Ques.43.
What are the different keyboard operations that can be performed in selenium?
What are the different keyboard operations that can be performed in selenium?
Ans. The different keyboard
operations that can be performed in selenium are-
operations that can be performed in selenium are-
sendKeys(“sequence of
characters”) – Used for passing character sequence to an input or textbox
element.
characters”) – Used for passing character sequence to an input or textbox
element.
pressKey(“non-text
keys”) – Used for keys like control, function keys etc that are non-text.
keys”) – Used for keys like control, function keys etc that are non-text.
releaseKey(“non-text
keys”) – Used in conjuntion with keypress event to simulate releasing a
key from keyboard event.
keys”) – Used in conjuntion with keypress event to simulate releasing a
key from keyboard event.
Ques.44.
What are the different mouse actions that can be performed?
What are the different mouse actions that can be performed?
Ans. The different mouse
evenets supported in selenium are
evenets supported in selenium are
click(WebElement element)
doubleClick(WebElement
element)
element)
contextClick(WebElement
element)
element)
mouseDown(WebElement
element)
element)
mouseUp(WebElement element)
mouseMove(WebElement
element)
element)
mouseMove(WebElement
element, long xOffset, long yOffset)
element, long xOffset, long yOffset)
Ques.45.
Write the code to double click an element in selenium?
Write the code to double click an element in selenium?
Ans. Code to double click an
element in selenium-
element in selenium-
Actions action =
new Actions(driver)
new Actions(driver)
WebElement
element=driver.findElement(By.id(“elementId”));
element=driver.findElement(By.id(“elementId”));
action.doubleClick(element).perform();
Ques.46.
Write the code to right click an element in selenium?
Write the code to right click an element in selenium?
Code to right click an
element in selenium-
element in selenium-
Actions action =
new Actions(driver);
new Actions(driver);
WebElement
element=driver.findElement(By.id(“elementId”));
element=driver.findElement(By.id(“elementId”));
action.contextClick(element).perform();
Ques.47.
How to mouse hover an element in selenium?
How to mouse hover an element in selenium?
Ans. Code to mouse hover
over an element in selenium-
over an element in selenium-
Actions action =
new Actions(driver);
new Actions(driver);
WebElement
element=driver.findElement(By.id(“elementId”));
element=driver.findElement(By.id(“elementId”));
action.moveToElement(element).perform();
Ques.48.
How to fetch the current page URL in selenium?
How to fetch the current page URL in selenium?
Ans. Using getCurrentURL() command we can fetch the current page
URL-
URL-
driver.getCurrentUrl();
Ques.49.
How can we fetch title of the page in selenium?
How can we fetch title of the page in selenium?
Ans. Using driver.getTitle(); we can fetch the page title in
selenium. This method returns a string containing the title of the webpage.
selenium. This method returns a string containing the title of the webpage.
Ques.50.
How can we fetch the page source in selenium?
How can we fetch the page source in selenium?
Ans. Using driver.getPageSource(); we can fetch the page source
in selenium. This method returns a string containing the page source.
in selenium. This method returns a string containing the page source.
Ques.51.
How to verify tooltip text using selenium?
How to verify tooltip text using selenium?
Ans. Tooltips webelements
have an attribute of type ‘title’. By fetching the value of ‘title’ attribute
we can verify the tooltip text in selenium.
have an attribute of type ‘title’. By fetching the value of ‘title’ attribute
we can verify the tooltip text in selenium.
String toolTipText
= element.getAttribute(“title”);
= element.getAttribute(“title”);
Ques.52.
How to locate a link using its text in selenium?
How to locate a link using its text in selenium?
Ans. Using linkText() and
partialLinkText() we can locate a link. The difference between the two is
linkText matches the complete string passed as parameter to the link texts.
Whereas partialLinkText matches the string parameter partially with the link
texts.
partialLinkText() we can locate a link. The difference between the two is
linkText matches the complete string passed as parameter to the link texts.
Whereas partialLinkText matches the string parameter partially with the link
texts.
WebElement link1 =
driver.findElement(By.linkText(“testinggyann”));
driver.findElement(By.linkText(“testinggyann”));
WebElement link2 =
driver.findElement(By.partialLinkText(“test”));
driver.findElement(By.partialLinkText(“test”));
Ques.53.
What are DesiredCapabilities in selenium webdriver?
What are DesiredCapabilities in selenium webdriver?
Ans. Desired capabilities
are a set of key-value pairs that are used for storing or configuring browser
specific properties like its version, platform etc in the browser instances.
are a set of key-value pairs that are used for storing or configuring browser
specific properties like its version, platform etc in the browser instances.
Ques.54.
How can we find all the links on a web page?
How can we find all the links on a web page?
Ans. All the links are of
anchor tag ‘a’. So by locating elements of tagName ‘a’ we can find all the
links on a webpage.
anchor tag ‘a’. So by locating elements of tagName ‘a’ we can find all the
links on a webpage.
List<WebElement>
links = driver.findElements(By.tagName(“a”));
links = driver.findElements(By.tagName(“a”));
Ques.55.
What are some commonly encountered exceptions in selenium?
What are some commonly encountered exceptions in selenium?
Ans. Some of the commonly seen
exception in selenium are-
exception in selenium are-
NoSuchElementException –
When no element could be located from the locator provided.
When no element could be located from the locator provided.
ElementNotVisibleException –
When element is present in the dom but is not visible.
When element is present in the dom but is not visible.
NoAlertPresentException –
When we try to switch to an alert but the targetted alert is not present.
When we try to switch to an alert but the targetted alert is not present.
NoSuchFrameException – When
we try to switch to a frame but the targetted frame is not present.
we try to switch to a frame but the targetted frame is not present.
NoSuchWindowException – When
we try to switch to a window but the targetted window is not present.
we try to switch to a window but the targetted window is not present.
UnexpectedAlertPresentException
– When an unexpected alert blocks normal interaction of the driver.
– When an unexpected alert blocks normal interaction of the driver.
TimeoutException – When a command
execution gets timeout.
execution gets timeout.
InvalidElementStateException
– When the state of an element is not appropriate for the desired action.
– When the state of an element is not appropriate for the desired action.
NoSuchAttributeException –
When we are trying to fetch an attribute’s value but the attribute is not
correct
When we are trying to fetch an attribute’s value but the attribute is not
correct
WebDriverException – When
there is some issue with driver instance preventing it from getting launched.
there is some issue with driver instance preventing it from getting launched.
Ques.56.
How can we capture screenshots in selenium?
How can we capture screenshots in selenium?
Ans. Using getScreenshotAs method of Takes Screenshot interface
we can take the screenshots in selenium.
we can take the screenshots in selenium.
File scrFile =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile,
new File(“D:\testScreenShot.jpg”));
new File(“D:\testScreenShot.jpg”));
Ques.57.
How to handle dropdowns in selenium?
How to handle dropdowns in selenium?
Ans. Using Select class-
Select
countriesDropDown = new
Select(driver.findElement(By.id(“countries”)));
countriesDropDown = new
Select(driver.findElement(By.id(“countries”)));
dropdown.selectByVisibleText(“India”);
//or using index of the
option starting from 0 dropdown.selectByIndex(1);
option starting from 0 dropdown.selectByIndex(1);
//or using its value
attribute dropdown.selectByValue(“Ind”);
attribute dropdown.selectByValue(“Ind”);
Ques.58.
How to check which option in the dropdown is selected?
How to check which option in the dropdown is selected?
Ans. Using isSelected() method we can check the state of a
dropdown’s option.
dropdown’s option.
Select
countriesDropDown = new
Select(driver.findElement(By.id(“countries”)));
countriesDropDown = new
Select(driver.findElement(By.id(“countries”)));
dropdown.selectByVisibleText(“India”);
//returns true or false
value
value
System.out.println(driver.findElement(By.id(“India”)).isSelected());
Ques.59.
How can we check if an element is getting displayed on a web page?
How can we check if an element is getting displayed on a web page?
Ans. Using isDisplayed method we can check if an element is
getting displayed on a web page.
getting displayed on a web page.
driver.findElement(By
locator).isDisplayed();
locator).isDisplayed();
Ques.60.
How can we check if an element is enabled for interaction on a web page?
How can we check if an element is enabled for interaction on a web page?
Ans. Using isEnabled method we can check if an element is enabled
or not.
or not.
driver.findElement(By
locator).isEnabled();
locator).isEnabled();
Ques.61.
What is the difference between driver.findElement() and driver.findElements()
commands?
What is the difference between driver.findElement() and driver.findElements()
commands?
Ans. The difference between
driver.findElement() and driver.findElements() commands is- findElement()
returns a single WebElement (found first) based on the locator passed as
parameter. Whereas findElements() returns a list of WebElements, all satisfying
the locator value passed.
driver.findElement() and driver.findElements() commands is- findElement()
returns a single WebElement (found first) based on the locator passed as
parameter. Whereas findElements() returns a list of WebElements, all satisfying
the locator value passed.
Syntax of findElement()- WebElement textbox = driver.findElement(By.id(“textBoxLocator”));
Syntax of findElements()- List
<WebElement> elements = element.findElements(By.id(“value”));
<WebElement> elements = element.findElements(By.id(“value”));
Another difference between the two is- if no element is
found then findElement() throws NoSuchElementException whereas findElements()
returns a list of 0 elements.
found then findElement() throws NoSuchElementException whereas findElements()
returns a list of 0 elements.
Ques.62.
Explain the difference between implicit wait and explicit wait.?
Explain the difference between implicit wait and explicit wait.?
Ans. An implicit wait, while
finding an element waits for a specified time before throwing
NoSuchElementException in case element is not found. The timeout value remains
valid throughout the webDriver’s instance and for all the elements.
finding an element waits for a specified time before throwing
NoSuchElementException in case element is not found. The timeout value remains
valid throughout the webDriver’s instance and for all the elements.
driver.manage().timeouts().implicitlyWait(180,
TimeUnit.SECONDS);
TimeUnit.SECONDS);
Whereas, Explicit wait is
applied to a specified element only-
applied to a specified element only-
WebDriverWait wait
= new WebDriverWait(driver, 5);
= new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(ElementLocator));
It is advisable to use
explicit waits over implicit waits because higher timeout value of implicit
wait set due to an element that takes time to be visible gets applied to all
the
explicit waits over implicit waits because higher timeout value of implicit
wait set due to an element that takes time to be visible gets applied to all
the
elements. Thus increasing
overall execution time of the script. On the other hand, we can apply different
timeouts to different element in case of explicit waits.
overall execution time of the script. On the other hand, we can apply different
timeouts to different element in case of explicit waits.
Ques.63.
How can we handle window UI elements and window POP ups using selenium?
How can we handle window UI elements and window POP ups using selenium?
Ans. Selenium is used for
automating Web based application only(or browsers only). For handling window
GUI elements we can use AutoIT. AutoIT is a freeware used for automating window
GUI. The AutoIt scripts follow simple BASIC lanaguage like syntax and can be
easily integrated with selenium tests.
automating Web based application only(or browsers only). For handling window
GUI elements we can use AutoIT. AutoIT is a freeware used for automating window
GUI. The AutoIt scripts follow simple BASIC lanaguage like syntax and can be
easily integrated with selenium tests.
Ques.64.
What is Robot API?
What is Robot API?
Ans. Robot API is used for
handling Keyboard or mouse events. It is generally used to upload files to the
server in selenium automation.
handling Keyboard or mouse events. It is generally used to upload files to the
server in selenium automation.
Robot robot = new
Robot();
Robot();
//Simulate enter key action
robot.keyPress(KeyEvent.VK_ENTER);
Ques.65.
How to do file upload in selenium?
How to do file upload in selenium?
Ans. File upload action can
be performed in multiple ways-
be performed in multiple ways-
Using element.sendKeys(“path of file”) on the
webElement of input tag and type file i.e. the elements should be like –
webElement of input tag and type file i.e. the elements should be like –
<input
type=”file” name=”fileUpload”>
type=”file” name=”fileUpload”>
Using Robot API.
Using AutoIT API.
Ques.66.
How to handle HTTPS website in selenium? or How to accept the SSL untrusted
connection?
How to handle HTTPS website in selenium? or How to accept the SSL untrusted
connection?
Ans. Using profiles in
firefox we can handle accept the SSL untrusted connection certificate. Profiles
are basically set of user preferences stored in a file.
firefox we can handle accept the SSL untrusted connection certificate. Profiles
are basically set of user preferences stored in a file.
FirefoxProfile
profile = new FirefoxProfile();
profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
WebDriver driver =
new FirefoxDriver(profile);
new FirefoxDriver(profile);
Ques.67
How to do drag and drop in selenium?
How to do drag and drop in selenium?
Using Action class, drag and
drop can be performed in selenium. Sample code-
drop can be performed in selenium. Sample code-
Actions builder =
new Actions(driver);
new Actions(driver);
Action dragAndDrop
= builder.clickAndHold(SourceElement)
= builder.clickAndHold(SourceElement)
moveToElement(TargetElement).release(TargetElement.build();
dragAndDrop.perform();
Ques.68.
How to execute javascript in selenium?
How to execute javascript in selenium?
Ans. JavaScript can be
executed in selenium using JavaScriptExecuter. Sample code for javascript
execution-
executed in selenium using JavaScriptExecuter. Sample code for javascript
execution-
WebDriver driver =
new FireFoxDriver();
new FireFoxDriver();
if (driver instanceof
JavascriptExecutor) {
JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript(“{JavaScript
Code}”);
Code}”);
}
Ques.69.
How to handle alerts in selenium?
How to handle alerts in selenium?
Ans. In order to accept or
dismiss an alert box the alert class is used. This requires first switching to
the alert box and than using accept() or dismiss() command as the case may be.
dismiss an alert box the alert class is used. This requires first switching to
the alert box and than using accept() or dismiss() command as the case may be.
Alert alert =
driver.switchTo().alert();
driver.switchTo().alert();
//To accept the alert
alert.accept();
Alert alert =
driver.switchTo().alert();
driver.switchTo().alert();
//To cancel the alert box
alert.dismiss();
Ques.70.
What is HtmlUnitDriver?
What is HtmlUnitDriver?
Ans. HtmlUnitDriver is the
fastest WebDriver. Unlike other drivers (FireFoxDriver, ChromeDriver etc), the
HtmlUnitDriver is non-GUI, while running no browser gets launched.
fastest WebDriver. Unlike other drivers (FireFoxDriver, ChromeDriver etc), the
HtmlUnitDriver is non-GUI, while running no browser gets launched.
Ques.71.
How to handle hidden elements in Selenium webDriver?
How to handle hidden elements in Selenium webDriver?
Ans. Using javaScript
executor we can handle hidden elements
executor we can handle hidden elements
(JavascriptExecutor(driver)).executeScript(“document.getElementsByClassName(ElementLocator).click();”);
Ques.72.
What is Page Object Model or POM?
What is Page Object Model or POM?
Ans. Page Object Model(POM)
is a design pattern in selenium. A design pattern is a solution or a set of
standards that are used for solving commonly occuring software problems.
is a design pattern in selenium. A design pattern is a solution or a set of
standards that are used for solving commonly occuring software problems.
Now coming to POM – POM
helps to create a framework for maintaining selenium scripts. In POM for each
page of the application a class is created having the web elements belonging to
the page and methods handling the events in that page. The test scripts are
maintained in seperate files and the methods of the page object files are called
from the test scripts file.
helps to create a framework for maintaining selenium scripts. In POM for each
page of the application a class is created having the web elements belonging to
the page and methods handling the events in that page. The test scripts are
maintained in seperate files and the methods of the page object files are called
from the test scripts file.
Ques.73.
What are the advantages of POM?
What are the advantages of POM?
Ans. The advantages are POM
are-
are-
Using POM we can create an
Object Repository, a set of web elements in seperate files along with their
associated functions. There by keeping code clean.
Object Repository, a set of web elements in seperate files along with their
associated functions. There by keeping code clean.
For any change in UI(or web
elements) only page object files are required to be updated leaving test files
unchanged. It makes code reusable and maintable.
elements) only page object files are required to be updated leaving test files
unchanged. It makes code reusable and maintable.
Ques.74.
What is Page Factory?
What is Page Factory?
Ans. Page factory is an
implementation of Page Object Model in selenium. It provides @FindBy annotation
to find web elements and PageFactory.initElements() method to initialize all
web elements defined with @FindBy annotation.
implementation of Page Object Model in selenium. It provides @FindBy annotation
to find web elements and PageFactory.initElements() method to initialize all
web elements defined with @FindBy annotation.
public class
SamplePage {
SamplePage {
WebDriver driver;
@FindBy(id=”search”)
WebElement
searchTextBox;
searchTextBox;
@FindBy(name=”searchBtn”)
WebElement
searchButton;
searchButton;
//Constructor
public
samplePage(WebDriver driver){
samplePage(WebDriver driver){
this.driver = driver;
//initElements method to
initialize all elements
initialize all elements
PageFactory.initElements(driver,
this);
this);
}
//Sample method
public void
search(String searchTerm){
search(String searchTerm){
searchTextBox.sendKeys(searchTerm);
searchButton.click();
}
}
Ques.75.
What is an Object repository?
What is an Object repository?
Ans. An object repository is
centralized location of all the object or WebElements of the test scripts. In
selenium we can create object repository using Page Object Model and Page
Factory design patterns.
centralized location of all the object or WebElements of the test scripts. In
selenium we can create object repository using Page Object Model and Page
Factory design patterns.
Ques.76.
What is a data driven framework?
What is a data driven framework?
Ans. A data driven framework
is one in which the test data is put in external files like csv, excel etc
separated from test logic written in test script files. The test data drives
the test cases, i.e. the test methods run for each set of test data values.
TestNG provides inherent support for data driven testing using @dataProvider
annotation.
is one in which the test data is put in external files like csv, excel etc
separated from test logic written in test script files. The test data drives
the test cases, i.e. the test methods run for each set of test data values.
TestNG provides inherent support for data driven testing using @dataProvider
annotation.
Ques.77.
What is a keyword driven framework?
What is a keyword driven framework?
Ans. A keyword driven
framework is one in which the actions are associated with keywords and kept in
external files e.g. an action of launching a browser will be associated with
keyword – launchBrowser(), action to write in a textbox with keyword – writeInTextBox(webElement,
textToWrite) etc. The code to perform the action based on a keyword specified
in external file is implemented in the framework itself.
framework is one in which the actions are associated with keywords and kept in
external files e.g. an action of launching a browser will be associated with
keyword – launchBrowser(), action to write in a textbox with keyword – writeInTextBox(webElement,
textToWrite) etc. The code to perform the action based on a keyword specified
in external file is implemented in the framework itself.
In this way the test steps
can be written in a file by even a person of non-programming background once
all the identified actions are implemented.
can be written in a file by even a person of non-programming background once
all the identified actions are implemented.
Ques.78.
What is a hybrid framework?
What is a hybrid framework?
Ans. A hybrid framework is a
combination of one or more frameworks. Normally it is associated with
combination of data driven and keyword driven frameworks where both the test
data and test actions are kept in external files(in the form of table).
combination of one or more frameworks. Normally it is associated with
combination of data driven and keyword driven frameworks where both the test
data and test actions are kept in external files(in the form of table).
Ques.79.
What is selenium Grid?
What is selenium Grid?
Ans. Selenium grid is a tool
that helps in distributed running of test scripts across different machines
having different browsers, browser version, platforms etc in parallel. In
selenium grid there is hub that is a central server managing all the
distributed machines known as nodes.
that helps in distributed running of test scripts across different machines
having different browsers, browser version, platforms etc in parallel. In
selenium grid there is hub that is a central server managing all the
distributed machines known as nodes.
Ques.80.
What are some advantages of selenium grid?
What are some advantages of selenium grid?
Ans. The advantages of
selenium grid are-
selenium grid are-
It allows running test cases
in parallel thereby saving test execution time.
in parallel thereby saving test execution time.
Multi browser testing is
possible using selenium grid by running the test on machines having different
browsers.
possible using selenium grid by running the test on machines having different
browsers.
It is allows multi-platform
testing by configuring nodes having different operating systems.
testing by configuring nodes having different operating systems.
Ques.81.
What is a hub in selenium grid?
What is a hub in selenium grid?
Ans. A hub is server or a
central point in selenium grid that controls the test executions on the
different machines.
central point in selenium grid that controls the test executions on the
different machines.
Ques.82.
What is a node in selenium grid?
What is a node in selenium grid?
Ans. Nodes are the machines
which are attached to the selenium grid hub and have selenium instances running
the test scripts. Unlike hub there can be multiple nodes in selenium grid.
which are attached to the selenium grid hub and have selenium instances running
the test scripts. Unlike hub there can be multiple nodes in selenium grid.
Ques.83.
Explain the line of code Webdriver driver = new FirefoxDriver();.
Explain the line of code Webdriver driver = new FirefoxDriver();.
Ans. In the line of code
Webdriver driver = new FirefoxDriver(); ‘WebDriver’ is an interface and we are
creating an object of type WebDriver instantiating an object of FirefoxDriver
class.
Webdriver driver = new FirefoxDriver(); ‘WebDriver’ is an interface and we are
creating an object of type WebDriver instantiating an object of FirefoxDriver
class.
Ques.84
What is the purpose of creating a reference variable- ‘driver’ of type
WebDriver instead of directly creating a FireFoxDriver object or any other
driver’s reference in the statement Webdriver driver = new FirefoxDriver();?
What is the purpose of creating a reference variable- ‘driver’ of type
WebDriver instead of directly creating a FireFoxDriver object or any other
driver’s reference in the statement Webdriver driver = new FirefoxDriver();?
Ans. By creating a reference
variable of type WebDriver we can use the same variable to work with multiple
browsers like ChromeDriver, IEDriver etc.
variable of type WebDriver we can use the same variable to work with multiple
browsers like ChromeDriver, IEDriver etc.
Ques.85.
What is testNG?
What is testNG?
Ans. TestNG(NG for Next
Generation) is a testing framework that can be integrated with selenium or any
other automation tool to provide multiple capabilities like assertions,
reporting, parallel test execution etc.
Generation) is a testing framework that can be integrated with selenium or any
other automation tool to provide multiple capabilities like assertions,
reporting, parallel test execution etc.
Ques.86.
What are some advantages of testNG?
What are some advantages of testNG?
Ans. Following are the
advantages of testNG-
advantages of testNG-
TestNG provides different
assertions that helps in checking the expected and actual results.
assertions that helps in checking the expected and actual results.
It provides parallel
execution of test methods.
execution of test methods.
We can define dependency of
one test method over other in TestNG.
one test method over other in TestNG.
We can assign priority to
test methods in selenium.
test methods in selenium.
It allows grouping of test
methods into test groups.
methods into test groups.
It allows data driven
testing using @DataProvider annotation.
testing using @DataProvider annotation.
It has inherent support for
reporting.
reporting.
It has support for
parameterizing test cases using @Parameters annotation.
parameterizing test cases using @Parameters annotation.
Ques.87.
What is the use of testng.xml file?
What is the use of testng.xml file?
Ans. testng.xml file is used
for configuring the whole test suite. In testng.xml file we can create test
suite, create test groups, mark tests for parallel execution, add listeners and
pass parameters to test scripts. Later this testng.xml file can be used for
triggering the test suite.
for configuring the whole test suite. In testng.xml file we can create test
suite, create test groups, mark tests for parallel execution, add listeners and
pass parameters to test scripts. Later this testng.xml file can be used for
triggering the test suite.
Ques.88.
How can we pass parameter to test script using testNG?
How can we pass parameter to test script using testNG?
Ans. Using @Parameter
annotation and ‘parameter’ tag in testng.xml we can pass parameters to the test
script.
annotation and ‘parameter’ tag in testng.xml we can pass parameters to the test
script.
Sample testng.xml –
<suite
name=”sampleTestSuite”>
name=”sampleTestSuite”>
<test name=”sampleTest”>
<parameter
name=”sampleParamName” value=”sampleParamValue”/>
name=”sampleParamName” value=”sampleParamValue”/>
<classes>
<class name=”TestFile”
/>
/>
</classes>
</test>
</suite>
Sample test script-
public class
TestFile {
TestFile {
@Test
@Parameters(“sampleParamName”)
public void parameterTest(String paramValue)
{
{
System.out.println(“Value of
sampleParamName is – ” + sampleParamName);
sampleParamName is – ” + sampleParamName);
}
Ques.89.
How can we create data driven framework using testNG?
How can we create data driven framework using testNG?
Ans. Using @DataProvider we
can create a data driven framework in which data is passed to the associated
test method and multiple iteration of the test runs for the different test data
values passed from the @DataProvider method. The method annotated with
@DataProvider annotation return a 2D array of object.
can create a data driven framework in which data is passed to the associated
test method and multiple iteration of the test runs for the different test data
values passed from the @DataProvider method. The method annotated with
@DataProvider annotation return a 2D array of object.
//Data provider returning 2D
array of 3*2 matrix
array of 3*2 matrix
@DataProvider(name =
“dataProvider1”)
“dataProvider1”)
public Object[][] dataProviderMethod1() {
return new Object[][]
{{“kuldeep”,”rana”},
{“k1″,”r1”},{“k2″,”r2”}};
{{“kuldeep”,”rana”},
{“k1″,”r1”},{“k2″,”r2”}};
}
//This method is bound to
the above data provider returning 2D array of 3*2 matrix
the above data provider returning 2D array of 3*2 matrix
//The test case will run 3
times with different set of values
times with different set of values
@Test(dataProvider =
“dataProvider1”)
“dataProvider1”)
public void sampleTest(String s1, String s2)
{
{
System.out.println(s1 + ” ” +
s2);
s2);
}
Ques.90.
What is the use of @Listener annotation in TestNG?
What is the use of @Listener annotation in TestNG?
Ans. TestNG provides us
different kind of listeners using which we can perform some action in case an
event has triggered. Usually testNG listeners are used for configuring reports
and logging. One of the most widely used lisetner in testNG is ITestListener
interface. It has methods like onTestSuccess, onTestFailure, onTestSkipped etc.
We need to implement this interface creating a listener class of our own. After
that using the @Listener annotation, we can use specify that for a particular
test class, our customized listener class should be used.
different kind of listeners using which we can perform some action in case an
event has triggered. Usually testNG listeners are used for configuring reports
and logging. One of the most widely used lisetner in testNG is ITestListener
interface. It has methods like onTestSuccess, onTestFailure, onTestSkipped etc.
We need to implement this interface creating a listener class of our own. After
that using the @Listener annotation, we can use specify that for a particular
test class, our customized listener class should be used.
@Listeners(PackageName.CustomizedListenerClassName.class)
public class
TestClass {
TestClass {
WebDriver driver= new FirefoxDriver();
@Test
public void testMethod(){
//test logic
}
}
Ques.91.
What is the use of @Factory annotation in TestNG?
What is the use of @Factory annotation in TestNG?
Ans. @Factory annotation
helps in dynamic execution of test cases. Using @Factory annotation we can pass
parameters to the whole test class at run time. The parameters passed can be
used by one or more test methods of that class.
helps in dynamic execution of test cases. Using @Factory annotation we can pass
parameters to the whole test class at run time. The parameters passed can be
used by one or more test methods of that class.
Example – there are two
classes TestClass and the TestFactory class. Because of the @Factory annotation
the test methods in class TestClass will run twice with the data “k1”
and “k2”
classes TestClass and the TestFactory class. Because of the @Factory annotation
the test methods in class TestClass will run twice with the data “k1”
and “k2”
public class
TestClass{
TestClass{
private String str;
//Constructor
public TestClass(String str) {
this.str = str;
}
@Test
public void TestMethod() {
System.out.println(str);
}
}
public class TestFactory{
//The test methods in class TestClass will
run twice with data “k1” and “k2”
run twice with data “k1” and “k2”
@Factory
public Object[] factoryMethod() {
return new Object[] { new
TestClass(“K1”), new TestClass(“k2”) };
TestClass(“K1”), new TestClass(“k2”) };
}
}
Ques.92.
What is difference between @Factory and @DataProvider annotation?
What is difference between @Factory and @DataProvider annotation?
Ans. @Factory method creates
instances of test class and run all the test methods in that class with
different set of data.
instances of test class and run all the test methods in that class with
different set of data.
Whereas, @DataProvider is
bound to individual test methods and run the specific methods multiple times.
bound to individual test methods and run the specific methods multiple times.
Ques.93.
How can we make one test method dependent on other using TestNG?
How can we make one test method dependent on other using TestNG?
Ans. Using dependsOnMethods
parameter inside @Test annotation in testNG we can make one test method run
only after successful execution of dependent test method.
parameter inside @Test annotation in testNG we can make one test method run
only after successful execution of dependent test method.
@Test(dependsOnMethods
= { “preTests” })
= { “preTests” })
Ques.94.
How can we set priority of test cases in TestNG?
How can we set priority of test cases in TestNG?
Ans. Using priority
parameter in @Test annotation in TestNG we can define priority of test cases.
The default priority of test when not specified is integer value 0. Example-
parameter in @Test annotation in TestNG we can define priority of test cases.
The default priority of test when not specified is integer value 0. Example-
@Test(priority=1)
Ques.95.
What are commonly used TestNG annotations?
What are commonly used TestNG annotations?
Ans. The commonly used
TestNG annotations are-
TestNG annotations are-
@Test- @Test annotation
marks a method as Test method.
marks a method as Test method.
@BeforeSuite- The annotated
method will run only once before all tests in this suite have run.
method will run only once before all tests in this suite have run.
@AfterSuite-The annotated
method will run only once after all tests in this suite have run.
method will run only once after all tests in this suite have run.
@BeforeClass-The annotated
method will run only once before the first test method in the current class is
invoked.
method will run only once before the first test method in the current class is
invoked.
@AfterClass-The annotated
method will run only once after all the test methods in the current class have
been run.
method will run only once after all the test methods in the current class have
been run.
@BeforeTest-The annotated
method will run before any test method belonging to the classes inside the
<test> tag is run.
method will run before any test method belonging to the classes inside the
<test> tag is run.
@AfterTest-The annotated
method will run after all the test methods belonging to the classes inside the
<test> tag have run.
method will run after all the test methods belonging to the classes inside the
<test> tag have run.
Ques.96.
What are some common assertions provided by testNG?
What are some common assertions provided by testNG?
Ans. Some of the common assertions
provided by testNG are-
provided by testNG are-
assertEquals(String actual,
String expected, String message) – (and other overloaded data type in parameters)
String expected, String message) – (and other overloaded data type in parameters)
assertNotEquals(double
data1, double data2, String message) – (and other overloaded data type in
parameters
data1, double data2, String message) – (and other overloaded data type in
parameters
assertFalse(boolean
condition, String message)
condition, String message)
assertTrue(boolean
condition, String message)
condition, String message)
assertNotNull(Object object)
fail(boolean condition,
String message)
String message)
true(String message)
Ques.97.
How can we run test cases in parallel using TestNG?
How can we run test cases in parallel using TestNG?
Ans. In order to run the
tests in parallel just add these two key value pairs in suite-
tests in parallel just add these two key value pairs in suite-
parallel=”{methods/tests/classes}”
thread-count=”{number
of thread you want to run simultaneously}”.
of thread you want to run simultaneously}”.
<suite
name=”ArtOfTestingTestSuite” parallel=”methods”
thread-count=”5″>
name=”ArtOfTestingTestSuite” parallel=”methods”
thread-count=”5″>
Ques.98.
Name an API used for reading and writing data to excel files.
Name an API used for reading and writing data to excel files.
Ans. Apache POI API and
JXL(Java Excel API) can be used for reading, writing and updating excel files.
JXL(Java Excel API) can be used for reading, writing and updating excel files.
Ques.99.
Name an API used for logging in Java
Name an API used for logging in Java
Ans. Log4j is an open source
API widely used for logging in Java. It supports multiple levels of logging
like – ALL, DEBUG, INFO, WARN, ERROR, TRACE and FATAL.
API widely used for logging in Java. It supports multiple levels of logging
like – ALL, DEBUG, INFO, WARN, ERROR, TRACE and FATAL.
Ques.100.
What is the use of logging in automation?
What is the use of logging in automation?
Ans. Logging helps in
debugging the tests when required and also provides a storage of test’s runtime
behaviour.
debugging the tests when required and also provides a storage of test’s runtime
behaviour.
TESTNG
INTERVIEW
INTERVIEW
Ques.1.
What is testNG?
What is testNG?
Ans. TestNG(NG for Next
Generation) is a testing framework that can be integrated with selenium or any
other automation tool to provide multiple capabilities like assertions,
reporting, parallel test execution etc.
Generation) is a testing framework that can be integrated with selenium or any
other automation tool to provide multiple capabilities like assertions,
reporting, parallel test execution etc.
Ques.2.
What are some advantages of testNG?
What are some advantages of testNG?
Ans. Following are the
advantages of testNG-
advantages of testNG-
TestNG provides different
assertions that helps in checking the expected and actual results.
assertions that helps in checking the expected and actual results.
It provides parallel
execution of test methods.
execution of test methods.
We can define dependency of
one test method over other in TestNG.
one test method over other in TestNG.
We can assign priority to
test methods in selenium.
test methods in selenium.
It allows grouping of test
methods into test groups.
methods into test groups.
It allows data driven
testing using @DataProvider annotation.
testing using @DataProvider annotation.
It has inherent support for
reporting.
reporting.
It has support for
parameterizing test cases using @Parameters annotation.
parameterizing test cases using @Parameters annotation.
Ques.3.
What is the use of testng.xml file?
What is the use of testng.xml file?
Ans. The testng.xml file is
used for configuring the whole test suite. In testng.xml file, we can create
test suite, create test groups, mark tests for parallel execution, add
listeners and pass parameters to test scripts. We can also use this testng.xml
file for triggering the test suite from command prompt/terminal or Jenkins.
used for configuring the whole test suite. In testng.xml file, we can create
test suite, create test groups, mark tests for parallel execution, add
listeners and pass parameters to test scripts. We can also use this testng.xml
file for triggering the test suite from command prompt/terminal or Jenkins.
Ques.4.
What are some commonly used TestNG annotations?
What are some commonly used TestNG annotations?
Ans. The commonly used
TestNG annotations are-
TestNG annotations are-
@Test- @Test annotation
marks a method as Test method.
marks a method as Test method.
@BeforeSuite- The annotated
method will run only once before all tests in this suite have run.
method will run only once before all tests in this suite have run.
@AfterSuite-The annotated
method will run only once after all tests in this suite have run.
method will run only once after all tests in this suite have run.
@BeforeClass-The annotated
method will run only once before the first test method in the current class is
invoked.
method will run only once before the first test method in the current class is
invoked.
@AfterClass-The annotated
method will run only once after all the test methods in the current class have
been run.
method will run only once after all the test methods in the current class have
been run.
@BeforeTest-The annotated
method will run before any test method belonging to the classes inside the
<test> tag is run.
method will run before any test method belonging to the classes inside the
<test> tag is run.
@AfterTest-The annotated
method will run after all the test methods belonging to the classes inside the
<test> tag have run.
method will run after all the test methods belonging to the classes inside the
<test> tag have run.
@DataProvider-The
@DataProvider annotation is used to pass test data to the test method. The test
method will run as per the number of rows of data passed via data provider method.
@DataProvider annotation is used to pass test data to the test method. The test
method will run as per the number of rows of data passed via data provider method.
Ques.5.
What are some common assertions provided by testNG?
What are some common assertions provided by testNG?
Ans. Some of the common assertions
provided by testNG are-
provided by testNG are-
assertEquals(String actual,
String expected, String message) – (and other overloaded data types in
parameter)
String expected, String message) – (and other overloaded data types in
parameter)
assertNotEquals(double
data1, double data2, String message) – (and other overloaded data types in
parameter)
data1, double data2, String message) – (and other overloaded data types in
parameter)
assertFalse(boolean
condition, String message)
condition, String message)
assertTrue(boolean
condition, String message)
condition, String message)
assertNotNull(Object object)
fail(boolean condition,
String message)
String message)
true(String message)
Ques.6.
How can we disable or prevent a test case from running?
How can we disable or prevent a test case from running?
Ans. By setting
“enabled” attribute as false, we can disable a test method from
running.
“enabled” attribute as false, we can disable a test method from
running.
@Test(enabled =
false)
false)
public void
testMethod() {
testMethod() {
//Test logic
}
Ques.7.
How can we make one test method dependent on other using TestNG?
How can we make one test method dependent on other using TestNG?
Ans. Using dependsOnMethods
parameter inside @Test annotation in testNG we can make one test method run
only after successful execution of dependent test method.
parameter inside @Test annotation in testNG we can make one test method run
only after successful execution of dependent test method.
@Test(dependsOnMethods
= { “preTests” })
= { “preTests” })
Ques.8.
How can we set priority of test cases in TestNG?
How can we set priority of test cases in TestNG?
Ans. We can define priority
of test cases using “priority” parameter in @Test annotation. The
tests with lower priority value will get executed first. Example-
of test cases using “priority” parameter in @Test annotation. The
tests with lower priority value will get executed first. Example-
@Test(priority=1)
Ques.9.
What is the default priority of test cases in TestNG?
What is the default priority of test cases in TestNG?
Ans. The default priority of
test when not specified is integer value 0. So, if we have one test case with
priority 1 and one without any priority then the test without any priority
test when not specified is integer value 0. So, if we have one test case with
priority 1 and one without any priority then the test without any priority
value will get executed
first (as default value will be 0 and tests with lower priority are executed
first).
first (as default value will be 0 and tests with lower priority are executed
first).
Ques.10.
How can we run a Test method multiple times in a loop(without using any data
provider)?
How can we run a Test method multiple times in a loop(without using any data
provider)?
Ans. Using invocationCount
parameter and setting its value to an integer value, makes the test method to
run n number of times in a loop.
parameter and setting its value to an integer value, makes the test method to
run n number of times in a loop.
@Test(invocationCount
= 10)
= 10)
public void
invocationCountTest(){
invocationCountTest(){
//Test logic
}
Ques.11.
What is threadPoolSize? How can we use it?
What is threadPoolSize? How can we use it?
Ans. The threadPoolSize
attribute specifies the number of thread to be assigned to the test method.
This is used in conjunction with invocationCount attribute. The number of
threads will get divided with the number of iterations of the test method
specified in the invocationCount attribute.
attribute specifies the number of thread to be assigned to the test method.
This is used in conjunction with invocationCount attribute. The number of
threads will get divided with the number of iterations of the test method
specified in the invocationCount attribute.
@Test(threadPoolSize
= 5, invocationCount = 10)
= 5, invocationCount = 10)
public void
threadPoolTest(){
threadPoolTest(){
//Test logic
}
Ques.12.
What is the difference between soft assertion and hard assertion in TestNG?
What is the difference between soft assertion and hard assertion in TestNG?
Ans. Soft assertions
(SoftAssert) allows us to have multiple assertions within a test method, even
when an assertion fails the test method contiues with the remaining test
execution. The result of all the assertions can be collated at the end using
softAssert.assertAll() method.
(SoftAssert) allows us to have multiple assertions within a test method, even
when an assertion fails the test method contiues with the remaining test
execution. The result of all the assertions can be collated at the end using
softAssert.assertAll() method.
@Test
public void
softAssertionTest(){
softAssertionTest(){
SoftAssert softAssert= new SoftAssert();
//Assertion failing
softAssert.fail();
System.out.println(“Failing”);
//Assertion passing
softAssert.assertEquals(1,
1);
1);
System.out.println(“Passing”);
//Collates test results and
marks them pass or fail
marks them pass or fail
softAssert.assertAll();
}
Here, even though the first
assertion fails still the test will continue with execution and print the
message below the second assertion.
assertion fails still the test will continue with execution and print the
message below the second assertion.
Hard assertions on the other
hand are the usual assertions prodived by TestNG. In case of hard assertion in
case of any failure, the test execution stops, preventing execution of any
further steps within the test method.
hand are the usual assertions prodived by TestNG. In case of hard assertion in
case of any failure, the test execution stops, preventing execution of any
further steps within the test method.
Ques.13.
How to fail a testNG test if it doesn’t get executed within a specified time?
How to fail a testNG test if it doesn’t get executed within a specified time?
Ans. We can use timeOut
attribute of @Test annotation. The value assigned to this timeOut attribute
will act as an upperbound, if test doesn’t get executed within this time frame
then it will fail with timeOut exception.
attribute of @Test annotation. The value assigned to this timeOut attribute
will act as an upperbound, if test doesn’t get executed within this time frame
then it will fail with timeOut exception.
@Test(timeOut =
1000)
1000)
public void
timeOutTest() throws InterruptedException {
timeOutTest() throws InterruptedException {
//Sleep for 2sec so that test will fail
Thread.sleep(2000);
System.out.println(“Will throw Timeout
exception!”);
exception!”);
}
Ques.14.
How can we skip a test case conditionally?
How can we skip a test case conditionally?
Ans. Using SkipException, we
can conditionally skip a test case. On throwing the skipException, the test
method me marked as skipped in the test execution report and any statement
after throwing the exception will not get executed.
can conditionally skip a test case. On throwing the skipException, the test
method me marked as skipped in the test execution report and any statement
after throwing the exception will not get executed.
@Test
public void
testMethod(){
testMethod(){
if(conditionToCheckForSkippingTest)
throw new SkipException(“Skipping the
test”);
test”);
//test logic
}
Ques.15.
How can we make sure a test method runs even if the test methods or groups on
which it depends fail or get skipped?
How can we make sure a test method runs even if the test methods or groups on
which it depends fail or get skipped?
Ans. Using
“alwaysRun” attribute of @Test annotation, we can make sure the test
method will run even if the test methods or groups on which it depends fail or
get skipped.
“alwaysRun” attribute of @Test annotation, we can make sure the test
method will run even if the test methods or groups on which it depends fail or
get skipped.
@Test
public void
parentTest() {
parentTest() {
Assert.fail(“Failed test”);
}
@Test(dependsOnMethods={“parentTest”},
alwaysRun=true)
alwaysRun=true)
public void
dependentTest() {
dependentTest() {
System.out.println(“Running even if
parent test failed”);
parent test failed”);
}
Here, even though the
parentTest failed, the dependentTest will not get skipped instead it will
executed because of “alwaysRun=true”. In case, we remove the
“alwaysRun=true” attribute from @Test then the report will show one
failure and one skipped test, without trying to run the dependentTest method.
parentTest failed, the dependentTest will not get skipped instead it will
executed because of “alwaysRun=true”. In case, we remove the
“alwaysRun=true” attribute from @Test then the report will show one
failure and one skipped test, without trying to run the dependentTest method.
Ques.16.
How can we pass parameter to test script using testNG?
How can we pass parameter to test script using testNG?
Ans. Using @Parameter
annotation and ‘parameter’ tag in testng.xml we can pass paramters to test
scripts.
annotation and ‘parameter’ tag in testng.xml we can pass paramters to test
scripts.
Sample testng.xml –
<suite
name=”sampleTestSuite”>
name=”sampleTestSuite”>
<test
name=”sampleTest”>
name=”sampleTest”>
<parameter
name=”sampleParamName” value=”sampleParamValue”/>
name=”sampleParamName” value=”sampleParamValue”/>
<classes>
<class name=”TestFile”
/>
/>
</classes>
</test>
</suite>
Sample test script-
public class
TestFile {
TestFile {
@Test
@Parameters(“sampleParamName”)
public void parameterTest(String paramValue)
{
{
System.out.println(“Value of sampleParamName
is – ” + sampleParamName);
is – ” + sampleParamName);
}
Ques.17.
How can we create data driven framework using testNG?
How can we create data driven framework using testNG?
Ans. Using @DataProvider we
can create a data driven framework in which data is passed to the associated
test method and multiple iteration of the test runs for the different test data
values passed from the @DataProvider method. The method annotated with
@DataProvider annotation return a 2D array of object.
can create a data driven framework in which data is passed to the associated
test method and multiple iteration of the test runs for the different test data
values passed from the @DataProvider method. The method annotated with
@DataProvider annotation return a 2D array of object.
//Data provider returning 2D
array of 3*2 matrix
array of 3*2 matrix
@DataProvider(name =
“dataProvider1”)
“dataProvider1”)
public
Object[][] dataProviderMethod1() {
Object[][] dataProviderMethod1() {
return new Object[][]
{{“kuldeep”,”rana”},
{“k1″,”r1”},{“k2″,”r2”}};
{{“kuldeep”,”rana”},
{“k1″,”r1”},{“k2″,”r2”}};
}
//This method is bound to
the above data provider returning 2D array of 3*2 matrix
the above data provider returning 2D array of 3*2 matrix
//The test case will run 3
times with different set of values
times with different set of values
@Test(dataProvider
= “dataProvider1”)
= “dataProvider1”)
public void sampleTest(String s1, String s2)
{
{
System.out.println(s1 + ” ” +
s2);
s2);
}
Ques.18.
What is the use of @Listener annotation in TestNG?
What is the use of @Listener annotation in TestNG?
Ans. TestNG provides us
different kind of listeners using which we can perform some action in case an
event has triggered. Usually testNG listeners are used for configuring reports
and logging. One of the most widely used lisetner in testNG is ITestListener
interface. It has methods like onTestSuccess, onTestFailure, onTestSkipped etc.
We need to implement this interface creating a listner class of our own. After
that using the @Listener annotation we can use specify that for a particular
test class our customized listener class should be used.
different kind of listeners using which we can perform some action in case an
event has triggered. Usually testNG listeners are used for configuring reports
and logging. One of the most widely used lisetner in testNG is ITestListener
interface. It has methods like onTestSuccess, onTestFailure, onTestSkipped etc.
We need to implement this interface creating a listner class of our own. After
that using the @Listener annotation we can use specify that for a particular
test class our customized listener class should be used.
@Listeners(PackageName.CustomizedListenerClassName.class)
public class
TestClass {
TestClass {
WebDriver driver= new
FirefoxDriver();@Test
FirefoxDriver();@Test
public void testMethod(){
//test logic
}
}
Ques.19.
What is the use of @Factory annotation in TestNG?
What is the use of @Factory annotation in TestNG?
Ans. @Factory annotation
helps in dynamic execution of test cases. Using @Factory annotation we can pass
parameters to the whole test class at run time. The parameters passed can be
used by one or more test methods of that class.
helps in dynamic execution of test cases. Using @Factory annotation we can pass
parameters to the whole test class at run time. The parameters passed can be
used by one or more test methods of that class.
Example – there are two
classes TestClass and the TestFactory class. Because of the @Factory annotation
the test methods in class TestClass will run twice with the data “k1”
and “k2”
classes TestClass and the TestFactory class. Because of the @Factory annotation
the test methods in class TestClass will run twice with the data “k1”
and “k2”
public class
TestClass{
TestClass{
private String str;
//Constructor
public TestClass(String str) {
this.str = str;
}
@Test
public void TestMethod() {
System.out.println(str);
}
}
public class TestFactory{
//The test methods in class TestClass will
run twice with data “k1” and “k2”
run twice with data “k1” and “k2”
@Factory
public Object[] factoryMethod() {
return new Object[] { new
TestClass(“K1”), new TestClass(“k2”) };
TestClass(“K1”), new TestClass(“k2”) };
}
}
Ques.20.
What is difference between @Factory and @DataProvider annotation?
What is difference between @Factory and @DataProvider annotation?
Ans. @Factory method creates
instances of test class and run all the test methods in that class with
different set of data.
instances of test class and run all the test methods in that class with
different set of data.
Whereas, @DataProvider is
bound to individual test methods and run the specific methods multiple times.
bound to individual test methods and run the specific methods multiple times.
Ques.21.
How can we run test cases in parallel using TestNG?
How can we run test cases in parallel using TestNG?
Ans. In order to run the
tests in parallel just add these two key value pairs in suite-
tests in parallel just add these two key value pairs in suite-
parallel=”{methods/tests/classes}”
thread-count=”{number of thread you
want to run simultaneously}”.
want to run simultaneously}”.
<suite
name=”testingyannSuite” parallel=”methods”
thread-count=”5″>
name=”testingyannSuite” parallel=”methods”
thread-count=”5″>



