Selenium Interview Q & A
Selenium Interview Q & A
Selenium Interview Q & A
– Selenium Grid gives the flexibility to distribute your test cases for execution.
– The machines running the nodes need not be the same platform as that of
the hub.
-JUnit
-Cucumber
-Robot Framework
-Appium
-Protractor
9) What is the difference between Soft Assert and Hard Assert in Selenium?
Hard Assert throws an AssertException immediately when an assert
statement fails and test suite continues with next @Test. It marks method as
fail if assert condition gets failed and the remaining statements inside the
method will be aborted.
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(driver.findElements(By.Xpath(“value”)).size()!=0){
System.out.println(“Element is present”);
}else{
System.out.println(“Element is absent”);
}
if(driver.findElement(By.Id(“submit”)).isEnabled()){
System.out.println(“Element is enabled”);
}else{
System.out.println(“Element is disabled”);
}
if(driver.getPageSource().contains(“Text”)){
System.out.println(“Text is present”);
}else{
System.out.println(“Text is not present”);
}
12) What are the different types of exceptions you have faced in Selenium
WebDriver?
Different types of exceptions in Selenium are:
– NoSuchElementException
-NoSuchWindowException
-NoSuchFrameException
-NoAlertPresentException
-ElementNotVisibleException
-ElementNotSelectableException
-TimeoutException
13) How to login into any site if it is showing an authentication pop-up for
Username and Password?
To work with Basic Authentication pop-up (which is a browser dialogue
window), you just need to send the user name and password along with the
application URL.
Syntax:
driver.get("http://admin:[email protected]");
Syntax:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Syntax:
17) How to input text into the text box fields without calling the sendKeys()?
We can use Javascript action to enter the value in text box.
Syntax:
driver.findElement(By.Id(“textbox_id”)).clear();
Syntax:
driver.wait(5);
– navigate().to();
-navigate().forward();
-navigate().back();
-navigate().refresh();
driver.getCurrentUrl();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
5) What are the different ways for refreshing the page using Selenium
WebDriver?
Browser refresh operation can be performed using the following ways in
Selenium:
– Refresh method
driver.manage().refresh();
– Get method
driver.get(“https://www.google.com”);
driver.get(driver.getCurrentUrl());
-Navigate method
driver.get(“https://www.google.com”);
driver.navigate.to(driver.getCurrentUrl());
-SendKeys method
driver. findElement(By.id("username")).sendKeys(Keys.F5);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.getElementById('displayed-text').value='text123'");
8) How can you find broken links in a page using Selenium WebDriver?
List<WebElement> elements = driver.findElements(By.tagName(“a”));
List finalList = new ArrayList();
for (WebElement element : elementList){
if(element.getAttribute("href") != null){
finalList.add(element);
}
}
return finalList;
In case, when selenium locators do not work you can use JavaScriptExecutor.
You can use JavaScriptExecutor to perform a desired operation on a web
element.
-Since the Object Repository is independent of test cases, multiple tests can
use the same object repository
-Reusability of code
@FindBy(id = “userName”)
WebElement txt_UserName;
OR
PageFactory.initElements(driver, Login.class);
17) What is the difference between Page Object Model and Page Factory?
Page Object Model is a design pattern to create an Object Repository for web
UI elements. However, Page Factory is a built-in class in Selenium for
maintaining object repository.
-Since the Object Repository is independent of test cases, multiple tests can
use the same object repository
-Re-usability of code
driver.get(baseUrl);
WebElement uploadElement = driver.findElement(By.id("uploadfile_0"));
// enter the file path onto the file-selection input field
uploadElement.sendKeys("C:\\newhtml.html");
Ex:
WebElement fr = driver.findElementById("theIframe");
driver.switchTo().frame(fr);
6) Have you used any cross browser testing tool to run Selenium Scripts on
cloud?
Below tools can be used to run selenium scripts on cloud:
-SauceLabs
-CrossBrowserTesting
7) What are the DesiredCapabitlies in Selenium WebDriver and their use?
The Desired Capabilities Class helps us to tell the webdriver, which
environment we are going to use in our test script.
11) What are Annotations and what are the different annotations available
in TestNG?
Annotations in TestNG are lines of code that can control how the method
below them will be executed. They are always preceded by the @ symbol.
-@BeforeSuite: The annotated method will be run only once before all tests in
this suite have run.
-@AfterSuite: The annotated method will be run only once after all tests in
this suite have run.
-@BeforeClass: The annotated method will be run only once before the first
test method in the current class is invoked.
-@AfterClass: The annotated method will be run only once after all the test
methods in the current class have run.
-@BeforeTest: The annotated method will be run before any test method
belonging to the classes inside the <test> tag is run.
-@AfterTest: The annotated method will be run after all the test methods
belonging to the classes inside the <test> tag have run.
-@BeforeGroups: The list of groups that this configuration method will run
before. This method is guaranteed to run shortly before the first test method
that belongs to any of these groups is invoked.
-@AfterGroups: The list of groups that this configuration method will run
after. This method is guaranteed to run shortly after the last test method that
belongs to any of these groups is invoked.
-@BeforeMethod: The annotated method will be run before each test
method.
-@AfterMethod: The annotated method will be run after each test method.
-@DataProvider: Marks a method as supplying data for a test method. The
annotated method must return an Object[ ][ ], where each Object[ ] can be
assigned the parameter list of the test 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.
-@Factory: Marks a method as a factory that returns objects that will be used
by TestNG as Test classes. The method must return Object[ ].
-@Listeners: Defines listeners on a test class.
-@Parameters: Describes how to pass parameters to a @Test method.
-@Test: Marks a class or a method as a part of the test
12) What is TestNG Assert and list out some common assertions supported
by TestNG?
Asserts helps us to verify the conditions of the test and decide whether test
has failed or passed. A test is considered successful ONLY if it is completed
without throwing any exception.
-assertEqual
-assertTrue
-assertFalse
<suite name=“TestSuite”>
<test name=“Test1”>
<classes>
<class name=“TestClass” />
</classes>
</test>
</suite>
Step 3: Run the test by right click on the testng xml file and select Run
As > TestNG Suite
@Test(priority = 0)
public void One() {
System.out.println("This is the Test Case number One");
}
@Test(priority = 1)
public void Two() {
System.out.println("This is the Test Case number Two");
}
@Parameters({“name”,”searchKey”})
@DataProvider(name=“SearchProvider”)
-IAnnotationTransformer
-IAnnotationTransformer2
-IConfigurable
-IConfigurationListener
-IExecutionListener
-IHookable
-IInvokedMethodListener
-IInvokedMethodListener2
-IMethodInterceptor
-IReporter
-ISuiteListener
-ITestListener
-DataDriven
-KeywordDriven
-Hybrid
-Minimal manual intervention: You need not input test data or run test scripts
manually and then keep monitoring the execution.
-Easy Reporting: The reporting module within framework can handle all the
report requirements.
-Segregation: A framework helps segregate the test script logic and the
corresponding test data. The Test data can be stored into an external
database like property files, xml files, excel files, text files, CSV files, ODBC
repositories etc.
24) Which Test Automation Framework you are using and why?
Cucumber Selenium Framework has now a days become very popular test
automation framework in the industry and many companies are using it
because its easy to involve business stakeholders and easy to maintain.
25) Mention the name of the Framework which you are using currently in
your project, explain it in details along with its benefits?
Framework consists of the following tools:
-Excel files: Excel files are used to pass multiple sets of data to the application.
-PageObject : It consists of all different page classes with their objects and
methods
-TestData: It stores the data files, Script reads test data from external data
sources and executes test based on it
-TestRunner: It is the starting point for Junit to start executing your tests
6) What are the various keywords that are used in Cucumber for writing a
scenario?
Most common keywords used in Cucumber are:
– Feature
– Background
– Scenario
– Given
– When
– Then
– And
– But
7) What is Scenario Outline in Cucumber and its purpose?
Same scenario can be executed for multiple sets of data using scenario
outline. The data is provided by a tabular structure.
Scenario: Login
The user logins to the site part of the step (the text following the Given
keyword) will match the following step definition:
Example:
| username | password |
| username1 | password1 |
| username2 | password2 |
25) Explain the purpose of keywords that are used for writing a scenario in
Cucumber?
– Feature: The purpose of the Feature keyword is to provide a high-level
description of a software feature, and to group related scenarios.
– Scenario: In addition to being a specification and documentation, a
scenario is also a test. As a whole, your scenarios are an executable
specification of the system.
– Given: steps are used to describe the initial context of the system – the
scene of the scenario. It is typically something that happened in the past.
– When: steps are used to describe an event, or an action. This can be a
person interacting with the system, or it can be an event triggered by another
system.
– Then: steps are used to describe an expected outcome, or result.
– Scenario Outline: This keyword can be used to run the same Scenario
multiple times, with different combinations of values.
– Background: It allows you to add some context to the scenarios in the
feature. It can contain one or more Given steps.
2) Can you arrange the below testng.xml tags from parent to child?
<test>
<suite>
<class>
<methods>
<classes>
<suite><test><classes><class><methods>
<groups>
<define name="include-groups">
</define>
<define name="exclude-groups">
</define>
<run>
</run>
</groups>
<classes>
</classes>
</test>
</suite>
8) How to exclude a particular test method from a test case execution using
TestNG?
<suite name="Sample Test Suite" verbose="1" >
<classes>
<class name="com.test.sample">
<methods>
</methods>
</class>
</classes>
</test>
</suite>
<groups>
<run>
<exclude name="integration"></exclude>
</run>
</groups>
<test name="Test">
<classes>
</classes>
</test>
</suite>
12) What are the different ways to produce reports for TestNG results?
There are two ways to generate a report with TestNG −
Listeners − For implementing a listener class, the class has to implement the
org.testng.ITestListener interface. These classes are notified at runtime by
TestNG when the test starts, finishes, fails, skips, or passes.
Reporters − For implementing a reporting class, the class has to implement an
org.testng.IReporter interface. These classes are called when the whole suite
run ends. The object containing the information of the whole test run is
passed to this class when called.
<suite name="testSuite">
<class name="sample">
<methods>
<exclude name="smoke.*"/>
</methods>
</class>
</classes>
</test>
</suite>
14) What is the time unit we specify in test suites and test cases?
Time unit is Milliseconds
@Test(invocationCount = 10)
System.out.println("Invocation method");
Example: Start a thread pool, which contains 3 threads, and run the test
method 3 times
@Test(invocationCount = 3, threadPoolSize = 3)
@Test(timeOut=5000)
Thread.sleep(3000);
@Test (priority=2)
driver.get("http://www.google.co.in");
@Test
@Parameters("name")
<classes>
</classes>
</test>
</suite>
4) What are the popular test automation tools for functional testing?
– Selenium
– Unified Functional Testing
– Test Complete
– Ranorex
– Tosca
10) What is the difference between Selenium IDE, Selenium RC and Selenium
WebDriver?
Selenium IDE:
– It only works in Mozilla browser.
– It supports Record and playback
– Doesn’t required to start server before executing the test script.
– It is a GUI Plug-in
– Core engine is Javascript based
– Very simple to use as it is record & playback.
– It is not object oriented
– It does not supports listeners
– It does not support to test iphone/Android applications
Selenium RC:
– It supports with all browsers like Firefox, IE, Chrome, Safari, Opera etc.
– It doesn’t supports Record and playback
– Required to start server before executing the test script.
– It is standalone java program which allow you to run Html test suites.
– Core engine is Javascript based
– It is easy and small API
– API’s are less Object oriented
– It does not supports listeners
– It does not support to test iphone/Android applications
Selenium Webdriver:
– It supports with all browsers like Firefox, IE, Chrome, Safari, Opera etc.
– It doesn’t supports Record and playback
– Doesn’t required to start server before executing the test script.
– It is a core API which has binding in a range of languages.
– Interacts natively with browser application
– As compared to RC, it is bit complex and large API.
– API’s are entirely Object oriented
– It supports the implementation of listeners
– It support to test iphone/Android applications
14) What is Same Origin Policy and how it can be handled? How to overcome
same origin policy through web driver?
Selenium uses java script to drives tests on a browser. Selenium injects its
own js to the response which is returned from aut. But there is a java script
security restriction (same origin policy) which lets you modify html of page
using js only if js also originates from the same domain as html.
assertEquals(expectedTitle,actualTitle);
builder.moveToElement(hoverElement).perform();
5) In Selenium IDE, what are the element locators that can be used to locate
the elements on web page?
– ID
– Name
– Link Text
– CSS Selector
– DOM
– XPATH
6) How can you convert any Selenium IDE tests from Selenese to other other
language?
Script can be exported to other programming languages. To change the
script format, open “Options” menu, select “Format” command, and then
choose one of these programming languages from the menu.
7) Using Selenium IDE, is it possible to get data from a particular HTML table
cell?
Verifytext can be used to verify text exist within the table.
9) In which format does the source view show the script in Selenium IDE?
Script is displayed in HTML format
10) Explain, how you can insert a start point in Selenium IDE?
We can insert a start point in the following ways:
– Right click on the command where the start point has to be set and select
‘Set/Clear Start Point’.
– Select the particular command and press ‘s’ or ‘S’ (shortcut key) for the
same.
11) What are regular expressions and how you can use them in Selenium
IDE?
A regular expression is a sequence of characters that define a search pattern.
Usually such patterns are used by string searching algorithms for “find” or
“find and replace” operations on strings, or for input validation.
Regular expressions can be used to match different content types on a web
page – Links, elements and text.
13) How you will handle switching between multiple windows in Selenium
IDE?
The selectWindow | tab=x and selectWindow | title=y commands switch
between browser tabs. You can use it with title=(title of tab to be selected) or,
often easier, use tab= with number of the tab (e. g 0,1,2,…).
selectWindow | TAB=OPEN | https://newwebsiteURL.com – this opens a new
tab and loads the website with the given URL.
14) How you will verify the specific position of an Web Element in Selenium
IDE?
Selenium IDE indicates the position of an element by measuring (in pixels)
how far it is from the left or top edge of the browser window using the below
commands:
verifyElementPositionLeft – verifies if the specified number of pixels match the
distance of the element from the left edge of the page.
verifyElementPositionTop – verifies if the specified number of pixels match the
distance of the element from the top edge of the page.
15) How you will retrieve the message in an Alert box in Selenium IDE?
We can use the storeAlert command to retrieve the alert message and store it
in a variable.
20) Can I control the speed and pause the test executed in Selenium IDE?
We can control the speed of the test by using the set speed command. The
pause command is a simple wait command and useful to delay the
execution of the automated testing for the specified time.
25) How to set a global base URL for every test case of one test suite file in
Selenium IDE?
Set an Environment variable to store the base URL and use it in every test
case.
3) What are different versions of Selenium available you have used and
what are the additional features you have seen from the previous versions?
Mostly worked with version 3 but now version 4 is going to be released.
Following are additional features which are expected in new version:
– Selenium 4 WebDriver is completely W3C Standardized
– The Selenium IDE support for Chrome is available now
– Improved Selenium Grid
– Better Debugging
– Better Documentation
5) What are the two most common practices for automation testing?
– Identify which test cases can be automated and which cannot be
automated.
– Do not rely completely on UI Automation.
8) What are the main traits of a good Software Test Automation framework?
Maintainability, Reliability, Flexibility, Efficiency, Portability, Robustness, and
Usability are main attributes of a good automation framework.
9) What are the challenges have you faced with Selenium and how did you
overcome them?
– Handling dynamic content: We can use Implicit Wait or Explicit Wait to
overcome this challenge
– Handling popup up windows: We can use getWindowHandle and
getWindowHandles methods to handle popups.
– Handling alerts: We can use methods provided by Alert interface to handle
an alert.
– Handling false positives: We can use different Assertions to look out for false
positives.
– Synchronization issues: We can use different wait methods provided by
selenium.
– Window based dialogs: We can use AutoIt tool to automate window based
dialogs
11) What are the benefits does WebDriver have over Selenium RC?
– Webdriver architecture is simpler than RC
– Webdriver is also faster than RC
– WebDriver interacts with page elements in a more realistic way
– WebDriver’s API is simpler than Selenium RC’s
– WebDriver can support the headless HtmlUnit browser but RC cannot
14) Which of Java. C-Sharp or Ruby can we use with Selenium Grid?
All the languages can be used with Selenium Grid.
15) What are Selenium Grid Extras and the additional features does it add to
Selenium Grid?
Selenium Grid Extras is a project that helps you set up and manage your local
Selenium Grid. Below are the additional features:
– Killing any browser instance by name
– Stopping any Process by PID
– Moving mouse to specific location
– Get Memory usage and disk statistics
– Automatically upgrade WebDriver binaries
– Restart node after a set number of test executions
– Central storage of configurations for all nodes on the HUB server
– Screenshots at the OS level
21) What are the different methods which can be used to verify the
existence of an element on a web page?
– driver.findElements(By.xpath(“value”)).size() != 0
– driver.findElement(By.id(id)).isDisplayed()
– driver.findElement(By.id(id)).isEnabled()
22) What is XPath Axes and what are the different Axes available?
XPath axes search different nodes in XML document from current context
node. XPath Axes are the methods used to find dynamic elements.
– following: Selects all elements in the document of the current node
– ancestor: The ancestor axis selects all ancestors element (grandparent,
parent, etc.) of the current node
– child: Selects all children elements of the current node
– preceding: Select all nodes that come before the current node
– following-sibling: Select the following siblings of the context node.
– parent: Selects the parent of the current node
– descendant: Selects the descendants of the current node
23) How to fetch an element when its attributes are changing frequently?
We can use different XPath methods like contains(), using or/and, starts-with,
text(),ends-with
24) What are the different ways to click on a button using Selenium?
– using click() method
– using return key: sendKeys(Keys.Return)
– using JavaScriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(“document.getElementsByName(‘login’)[0].click()”);
– using Actions class
Actions actions = new Actions(driver);
actions.moveToElement(button).click().perform();
25) What are the different types of Exceptions in Selenium?
– NoSuchElementException
– NoSuchWindowException
– NoSuchFrameException
– NoAlertPresentException
– InvalidSelectorException
– ElementNotVisibleException
– ElementNotSelectableException
– TimeoutException
– NoSuchSessionException
– StaleElementReferenceException
try{
driver.findElement(by.id("button")).click();
catch(NoSuchElementException e){
}
2) There are four browser windows opened and you don’t have any idea
where the required element is present. What will be your approach to find
that element?
– use getWindowHandles() method to get Window handles of all browser
windows
– use switchTo() method to switch to each browser window using the handle
id
– Find the element in each browser window and close the window if not
present
- dismiss()
driver.switchTo().alert().dismiss();
- accept()
driver.switchTo().alert().accept();
8) Give an example for method overloading concept that you have used in
Selenium?
Implicit Wait in Selenium use method overloading as we can provide different
Timestamp or TimeUnit like SECONDS, MINUTES, etc.
9) How do you select a value from a drop-down field and what are the
different methods available?
We can select value from drop-down using methods of Select class. Following
are the methods:
– selectByVisibleText
– selectByValue
– selectByIndex
elements.selectByVisibleText("Selenium");
elements.selectByIndex(1);
10) When your XPath is matching more than one element, how do you
handle it to locate the required element?
We can use index of the element to locate it or we can use different Xpath
axes methods to locate the element like Following, Ancestor, Child, Preceding
or Following-sibling
11) How do you capture screen-shots in Selenium and what is the best place
to have the screen-shot code?
//Convert web driver object to TakeScreenshot
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(SrcFile, DestFile);
12) Write the code for connecting to Excel files and other operations?
XSSFWorkbook srcBook = new XSSFWorkbook("Demo.xlsx");
int rownum=rowcounter;
XSSFCell cell1=sourceRow.getCell(0);
pdf.parse();
15) How do you debug your automation code when it is not working as
expected?
– Add breakpoints on the lines of code where it is not working
– Use different actions like F7(Step Into), F8(Step Over), F9(Step Out) to debug
the problem
16) What are the end methods you use for verifying whether the end result is
achieved by our Selenium automation scripts?
We can use different assertion methods available in different test frameworks
like TestNG or Junit.
17) How do you clear the cookies of a browser using Selenium, before
starting the execution?
driver.manage().deleteAllCookies();
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
@Parameters("browser")
if(browser.equalsIgnoreCase("firefox")){
else if(browser.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver",".\\chromedriver.exe");
testng.xml:
<test name="ChromeTest">
<classes>
<class name="com.qascript.crossbrowsertests">
</class>
</classes>
</test>
<test name="FirefoxTest">
<classes>
<class name="com.qascript.crossbrowsertests">
</class>
</classes>
</test>
</suite>
When a test script is executed with the help of WebDriver, the following tasks
are performed in the background:
– An HTTP request is generated and it is delivered to the browser driver for
every Selenium Command.
– The HTTP request is received by the driver through an HTTP server.
– All the steps/instructions to be executed on the browser is decided by an
HTTP server.
– The HTTP server then receives the execution status and in turn sends it back
to the automation scripts.
driver.get("https://qascript.com)
String dot="9/October/2018";
String date,month,year;
String caldt,calmonth,calyear;
/*
*/
String dateArray[]= dot.split("/");
date=dateArray[0];
month=dateArray[1];
year=dateArray[2];
driver.get("http://cleartrip.com");
driver.findElement(By.id("DepartDate")).click();
WebElement cal;
cal=driver.findElement(By.className("calendar"));
calyear=driver.findElement(By.className("ui-datepicker-year")).getText();
/**
*/
while (!calyear.equals(year))
driver.findElement(By.className("nextMonth")).click();
calyear=driver.findElement(By.className("ui-datepicker-year")).getText();
calmonth=driver.findElement(By.className("ui-datepicker-month")).getText();
/**
*/
while (!calmonth.equalsIgnoreCase(month))
{
driver.findElement(By.className("nextMonth ")).click();
calmonth=driver.findElement(By.className("ui-datepicker-month")).getText();
cal=driver.findElement(By.className("calendar"));
/**
*/
List<WebElement> rows,cols;
rows=cal.findElements(By.tagName("tr"));
cols=rows.get(i).findElements(By.tagName("td"));
caldt=cols.get(j).getText();
if (caldt.equals(date))
cols.get(j).click();
break;
}
12) Can I navigate back and forth in a browser using Selenium WebDriver?
Yes. We can use Navigate method to move back and forth in a browser.
driver.navigate().forward();
driver.navigate().back();
select.selectByIndex(2);
for(int i=0;i<totalRows.size-1;i++){
20) How many scripts are you writing and executing per a day?
It is all dependent on the automation framework and the application under
test.
22) Which reporting mechanism you have used in your Selenium projects?
We used the Maven Cucumber Reporting plugin to generate detailed html
reports.
23) Why did you choose Selenium in your project, when there are so many
tools?
We chose Selenium because of the following reasons:
– It is open source and free
– It is easy to learn and setup
– It is the most widely used and popular automation tool
– All the web applications in our project are compatible with Selenium
– Multi-browser and parallel testing is possible with Selenium
driver.getAttribute("innerhtml");
driver.findElement(By.id("chkbox")).click();
driver.findElement(By.id("chkbox")).isSelected();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", button);
9) How can you find the value of different attributes like name, class, value
of an element?
By using the getAttribute() method.
String name = driver.findElement(By.id("login")).getAttribute("name");
driver.findElement(By.id("btn")).isEnabled();
15) Write the program to locate/fetch all the links on a specific web page?
List<WebElements> allLinks = driver.findElements(By.tagName("a"));
16) How can we run test cases in parallel using TestNG?
By using the parallel attribute in testng.xml. The parallel attribute of suite tag
can accept four values:
– tests: All the test cases inside <test> tag of Testing 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 parall
17) How do you get the height and width of a text box field using Selenium?
We can get the height and width of a text box using getSize() method.
System.out.println(element.size());
23) Can you explain the line of code WebDriver driver = new
FirefoxDriver();?
It starts a new Firefox browser driver instance.
24) What could be the cause for Selenium WebDriver test to fail?
There could be many reasons for test failure. Some of them are listed below:
– Driver is null or not found
– Element is not found on the page
– Element is present but not interactable
– Page Synchronization issues
For a detailed view on all different locators in Selenium refer the following
page – https://qascript.com/selenium-locators/
8) How can we select elements by their attribute value using CSS Selector?
We need to provide the identifier type followed by the value in Css Selector to
select an element.
driver.findElement(By.id("Login")).submit();
12) What are some expected conditions that can be used in Explicit Waits?
– elementToBeClickable()
– elementToBeSelected()
– presenceOfElementLocated()
– visiblityOfElementLocated()
For a detailed view on all Selenium methods refer the following page –
https://qascript.com/selenium-webdriver-commands-cheat-sheet/
System.out.println(defaultItem );
DesiredCapabilities cap=DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
driver.findElement(By.id("checkbox")).click();
Selenium Java Interview
Questions and Answers Part-13
1) Explain how will automate drop down list ? How will you get size ? and text
present in it?
We can use the Select class and methods to automate drop down list. We will
get the size of the
items by using getOptions() method. We can iterate through each item and
get its text by using getText() method.
System.out.println(element.getText());
JavascriptExecutor JS = (JavascriptExecutor)webdriver;
JS.executeScript("document.getElementById('User').value='QAScript'");
6) How do you differentiate check box if more than one check box is existed
in your application?
We can first get the list of all check-boxes and then use index to perform
operation on a particular check-box.
elements.get(1).click();
element.click();
//Click on OK button
alert.accept();
alert.dismiss();
dropdown.selectByValue("1");
driver.findElement(By.xpath("//*[@name='username']//following-
sibling::input[@name='password']").sendKeys("password");
By byPageLoc = By.id("element");
wait.until(ExpectedConditions.elementToBeClickable(byPageLoc));
driver.findElement(By.id("element")).click();
if(!isElementDisplayed)
5) What is the API that is required for implementing Database Testing using
Selenium WebDriver?
JDBC api is required for Database testing.
11) Why and how will you use an Excel sheet in your Selenium project?
Excel sheet can be used as a data source from which we can read test data.
We can also use it for reporting.
12) How can you redirect browsing from a browser through some proxy?
Selenium provides a PROXY class to redirect browsing from a proxy.
proxy.setHTTPProxy(Proxy)
.setFtpProxy(Proxy)
.setSslProxy(Proxy)
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
wait.until(ExpectedConditions.visibilityOfElementLocated(element));
wait.until(ExpectedConditions.alertIsPresent());
js.executeScript("window.scrollBy(0,1000)");
19) Which files can be used as data source for different frameworks?
Text, Excel, XML and JSON can be used as data source files.
22) How to send alt or shift or control or enter or tab key in Selenium
WebDriver?
We can use sendKeys() method to send any key.
driver.findElement(element).sendKeys(Keys.TAB);
driver.manage().window().setSize(d);
24) How to switch to a new window (new tab) which opens up after you click
on a link?
String currentWindowHandle = driver.getWindowHandle();
if (window != currentWindowHandle){
driver.switchTo().window(window);
25) Can I call a single data provider method for multiple functions and
classes?
Yes. We can use a single data provider method for multiple functions.
14) What is the difference between Given, When, Then steps in feature file?
– Given steps are used to describe the initial context of the system – the
scene of the scenario.
– When steps are used to describe an event, or an action.
– Then steps are used to describe an expected outcome, or result.
20) What is the pattern of writing Given, When, Then, And, or But?
There is no strict pattern of writing these keywords and can be
interchangeably used based on the scenarios.
21) What is the use of glue property under Cucumber Options tag?
The glue is a part of Cucumber options that describes the location and path
of the step definition file.
@CucumberOptions(
features = "src/test/resources/features",
glue= {"stepDefs"},
monochrome = true
)
3) Full form of BDD?
BDD stands for Behaviour Driven Development. It is an Agile software
development
process that encourages collaboration among developers, QA and non-
technical or
business participants in a software project.
7) Name any two testing framework that can be integrated with Cucumber?
TestNG and Junit can be easily integrated with Cucumber.
8) Name any two build management tools that can be integrated with
Cucumber?
Maven and Ant are two build management tools which can be integrated
with cucumber.
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(
features = {
"src/test/resources/features"
},
plugin = {
"pretty",
"html:results/html",
"json:results/json/result.json",
"junit:results/junit/cucumber.xml"
},
monochrome = true
11) Name any advanced framework design that can be used with
Cucumber?
Page Object Model can be used with Cucumber.
13) Can you name any other BDD tools except Cucumber?
JBehave and SpecFlow
14) Can we write cucumber tags ( @smoke , @Run etc ) above feature
keyword in feature file?
Yes. We can write these cucumber tags above the feature keyword.
17) What is the plugin’s name that is used to integrate Cucumber into
Eclipse IDE?
Cucumber Eclipse Plugin can be used for Cucumber integration in Eclipse.
@CucumberOptions(
features = {
"src/test/resources/features"
},
plugin = {
"pretty",
"html:target/cucumber.html",
"json:target/cucumber.json"
}
4) What is the starting point of execution for feature files?
TestRunner is the starting point of execution.
@RunWith(Cucumber.class)
@CucumberOptions(
features = {
"src/test/resources/features"
},
plugin = {
"pretty",
"html:target/cucumber.html",
"json:target/cucumber.json"
@regression
@RunWith(Cucumber.class)
@CucumberOptions(
features = {
"src/test/resources/features"
},
plugin = {
"pretty",
"html:target/cucumber.html",
"json:target/cucumber.json",
"tags:@regression"
driver.quit();
24) What is the main difference between Scenario and Scenario outline?
– Scenario can be executed only once but Scenario outline can be used to
execute scenario multiple times with different sets of data
– Scenario Outline contains Examples with data table but Scenario doesn’t
contain examples
Examples:
| username | password |
| [email protected] | 123 |
@Test(priority=1)
@Test(priority=2)
3) Suppose you want to skip one test method from execution, how do you
skip it from execution?
We can use enabled method to enable or disable test in TestNG.
@Test(enabled=false)
<suite>
<test>
<classes>
<class>
<methods>
<classes>
<class name="com.example.TestRunner">
</class>
</classes>
</test>
</suite>
@Test
public void login(String username, String password){
System.out.println(username);
System.out.println(password);
<classes>
<class name="com.example.Tests">
</class>
</classes>
</test>
</suite>
<packages>
<package name="com.example"/>
</packages>
</test>
</suite>
driver.findElement(By.id("username")).sendKeys("qascript");
driver.findElement(By.id("password")).sendKeys("qascript123");
driver.findElement(By.id("submit")).click();
17) What problems you have faced while working with TestNG?
Working with DataProviders, Parallel execution and Listeners was challenging
in TestNG.
19) How to prioritize the tests in TestNG at Class level and Suite level?
Priority can be set for test methods and then we can use @BeforeSuite,
@BeforeClass methods to prioritize the tests at class and suite level.
20) Suppose I want to check a particular exception in TestNG. How will you
check?
@Test(expectedExceptions = ArithmeticException.class)
System.out.println("Exception occurred");
22) Do you know any third party reporting other than testng?
There are many third-party reporting like Extent Reports, Maven Cucumber
Reporting plugin.
24) How will you mark as method as a data provider using TestNG
annotation?
@Test(dataProvider="TestData")
actions.moveToElement(element).click().build().perform();
actions.dragAndDrop(fromElement,toElement).build().perform();
5) Can we use implicitly wait() and explicitly wait() together in the test
case?
Yes we can use implicitly and explicitly wait together in the same test.
6) What Is the syntax to get value from text box and store It In variable.?
String text = driver.findElement(by.id("textbox")).getAttribute("value");
FileUtils.copyFile(src,dest);
driver.switchTo().alert().dismiss();
driver.switchTo().alert().accept();
capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
10) What is Select Class in Selenium WebDriver and how to use it?
Select class is used to interact with select dropdowns on the webpage.
select.selectByVisibleText(element);
js.executeScript("window.scrollBy(0,200)");
17) If an explicit wait is 10 sec and the condition is met in 5 sec, will
driver move to execute next statement after 5 sec or it will wait for complete
10 sec then move?
Driver will move to next statement if the condition is met within 5 seconds and
will not wait
for 10 seconds.
18) If element is loaded by taking much time, how to handle this situation in
selenium?
We can use explicit or fluent wait methods to explicitly wait for the element.
21) How to change the URL on a webpage using selenium web driver?
We can use the navigate method to change the URL.
driver.navigateTo().url("https://qascript.com");
System.out.println(rows.size());
System.out.println(cols.size());
23) Write a program to return the row and column value like(3,4) for a given
data in web table?
String val = driver.findElement(by.xpath("//*[@id='table']/tbody/tr[3]/td[4]")).getText();