Selenium Interview Questions & Answers
Selenium Interview Questions & Answers
You must be wondering why I am covering all these factors right. I have taken couple of interviews and
based on my experience I will tell you what questions an Interviewer might ask.
If you are applying for Sr Automation Engg, Lead or Test Manager then be ready with some high-
level topics, which anyways I will be covering in this post.
However, if you are applying as a fresher, then you should be ready with some Java program and some
Selenium related code.
Before getting started keep in mind that there is not hard and fast rule that, the interviewer will ask
questions from a specific domain. It might cover multiple domain/tools.
1- What is Selenium Webdriver, Selenium RC, Selenium IDE and Selenium Grid and which version
you have used?
2-
Ans : Selenium Webdriver : WebDriver is a web automation tool that allows you to execute your
tests against different browsers, not just Firefox (unlike Selenium IDE). It is faster tham the
Selenium RC. Because it directly communicate with browser no need of external server like
Selenium RC.
Selenium IDE :Selenium IDE (Integrated Development Environment) is the simplest tool in the
Selenium Suite. It is a Firefox add-on that creates tests very quickly through its record-and-
playback functionality.
Selenium RC :Selenium Remote Control (RC) is a test tool that allows you to write automated
web application UI tests in any programming language against any HTTP website using any
mainstream JavaScript-enabled browser.
Selenium Grid: Selenium Grid is a part of the Selenium Suite that specializes on running
multiple tests across different browsers, operating systems, and machines in parallel.
************************------------------******************
3- Can you please explain Selenium Architecture?
4-
************************------------------******************
5- Have you worked on different browsers? Have you ever performed Cross browser testing?
Ans: Yes, I have worked on different browsers like Mozilla (the most common), Chrome, and IE,
performed cross browser testing demo. But while performing cross browser testing in my
automation framework. It was getting slower and data would not be going on to the proper
browser.
Ans- Every month a new browser is coming into market and it became very important to test our
web application on different browser. Selenium supports Cross browser testing. Please check the
detailed article here.
http://learn-automation.com/cross-browser-testing-using-selenium-webdriver/
************************------------------******************
Ans- Automation mainly focuses on regression testing, smoke testing, Sanity Testing and some
time you can for End to End test cases.
************************------------------******************
6- How to work with Chrome, IE or any other third party driver? Why we need separate driver for them?
Ans- Selenium by default supports only Firefox browser so in order to work with Chrome and IE browser
we need to download separate drivers for them and specify the path.
http://learn-automation.com/launch-chrome-browser-using-selenium-webdriver/
http://learn-automation.com/execute-selenium-script-in-ie-browser/
************************------------------******************
7- Have you created any framework? Which framework you have used?
Ans. Yes. I have created Data-Driven Framework and added some functionalities of Hybrid framework
and Page object model.
************************------------------******************
8- Can you please explainframework architecture?
************************------------------******************
9- What is POM (Page Object Model) and what is the need of it?
Ans- Page Object Model Framework has now a days become very popular test automation framework in
the industry and many companies are using it because of its easy test maintenance and reduces the
duplication of code.The main advantage of Page Object Model is that if the UI changes for any page, it
doesn’t require us to change any tests, we just need to change only the code within the page objects (Only
at one place). Many other tools which are using selenium, are following the page object model.
1. There is clean separation between test code and page specific code such as locators (or their use if
you’re using a UI map) and layout.2. There is single repository for the services or operations offered by
the page rather than having these services scattered throughout the tests.
************************------------------******************
10- What are the challenges you have faced while automating your application?
Ans- Challenges faced that are as follows:
Frequently changing UI. It always need to make changes in code most of the time.
Stuck somewhere while running automation scripts in chrome browser getting error that
element is not visible, element not found.
New kind of element like ck-editor, bootstrap calendar and dynamic web tables. But get
the solution always.
Reused of test scripts.
To be continued…….
************************------------------******************
11- What are the different type of exception available in Selenium? Have you faced any exception while
automation?
Ans- Yes. I have faced lots of exception. List are as follows:
1. ElementNotSelectableException
2. ElementNotVisibleException
3. NoSuchAttributeException
4. NoSuchElementException
5. NoSuchFrameException
6. TimeoutException
7. Element not visible at this point
************************------------------******************
12- What is Alert window/ JavaScript Alert and How to handle alert in Selenium Webdriver?
Ans: There are two types of alerts that we would be focusing on majorly:
1. Windows based alert pop ups
2. Web based alert pop ups
As we know that handling windows based pop ups is beyond WebDriver’s capabilities, thus we would
exercise some third party utilities to handle window pop ups. Handling pop up is one of the most
challenging piece of work to automate while testing web applications. Owing to the diversity in types of
pop ups complexes the situation even more.
Generally JavaScript popups are generated by web application and hence they can be easily controlled by
the browser.
Webdriver offers the ability to cope with javascript alerts using Alerts APIClick here to view Alert API
Details
Alert is an interface. There below are the methods that are used
<html>
<head>
<title>Selenium Easy Alerts Sample </title>
</head><body>
<h2>Alert Box Example</h2>
<fieldset>
<legend>Alert Box</legend><p>Click the button to display an alert box.</p>
<button onclick="alertFunction()">Click on me</button>
<script>
functionalertFunction()
{
alert("I am an example for alert box!");
}
</script>
</fieldset>
</body>
</html>
The below program will demonstrate you working on Alerts popup using above html file.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
publicclassPopupsHandling {
WebDriver driver=newFirefoxDriver();
@Test
publicvoidExampleForAlert() throws InterruptedException
{
driver.manage().window().maximize();
driver.get("file:///C:/path/alerts.html");
Thread.sleep(2000);
driver.findElement(By.xpath("//button[@onclick='alertFunction()']")).click();
Alert alert=driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
}
************************------------------******************
Window A has a link "Link1" and we need to click on the link (click event).
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
************************------------------******************
14- Have you ever worked on frames? In addition, how to handle frames in Selenium?
Yes. In Selenium to work with iFrames, we have different ways to handle frame depending on the need.
Please look at the below ways of handling frames.
driver.switchTo().frame(int arg0);
Select a frame by its (zero-based) index. That is, if a page has multiple frames (more than 1), the first
frame would be at index "0", the second at index "1" and so on.
Once the frame is selected or navigated , all subsequent calls on the WebDriver interface are made to that
frame. i.e the driver focus will be now on the frame. Whatever operations we try to perform on pages will
not work and throws element not found as we navigated / switched to Frame.
driver.switchTo().frame(WebElement frameElement);
Some times when there are multiple Frames (Frame in side a frame), we need to first switch to the parent
frame and then we need to switch to the child frame. below is the code snippet to work with multiple
frames.
public void switchToFrame(String ParentFrame, String ChildFrame) { try
{ driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame); System.out.println("Navigated to
innerframe with id " + ChildFrame + "which is present on frame with id" + ParentFrame); } catch
(NoSuchFrameException e) { System.out.println("Unable to locate frame with id " + ParentFrame + " or "
+ ChildFrame + e.getStackTrace()); } catch (Exception e) { System.out.println("Unable to navigate to
innerframe with id " + ChildFrame + "which is present on frame with id" + ParentFrame +
e.getStackTrace()); } }
After working with the frames, main important is to come back to the web page. if we don't switch back
to the default page, driver will throw an exception. Below is the code snippet to switch back to the default
content.
************************------------------******************
15- What are different locators available in Selenium?
Ans- There are 8 types of locators are available in selenium that are as follows:
id, xpath, name, byClassName, css selector, byTagName, linkText, partialLinkText.
************************------------------******************
16- Can you please explain XPATH and CSS technique? How to handle dynamic changing elements?
CSS Selector:
CSS mainly used to provide style rules for the web pages and we can use for identifying one or more
elements in the web page using css.
If you start using css selectors to identify elements, you will love the speed when compared with XPath.
Check this for more details on Css selectors examples
We can you use Css Selectors to make sure scripts run with the same speed in IE browser. CSS selector is
always the best possible way to locate complex elements in the page.
XPath Selector:
XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual
elements, attributes, or some other part of an XML document for specific processing
Here the advantage of specifying native path is, finding an element is very easy as we are mention the
direct path. But if there is any change in the path (if some thing has been added/removed) then that xpath
will break.
2. Relative Xpath.
In relative xpath we will provide the relative path, it is like we will tell the xpath to find an element by
telling the path in between.
Advantage here is, if at all there is any change in the html that works fine, until unless that particular path
has changed. Finding address will be quite difficult as it need to check each and every node to find that
path.
Example:
//table/tr/td
Dynamic CSS Selector in Selenium using multiple ways
Examples :
o Find css selector using single attribute. Syntax- tagname[attribute='value'] ,
Example- input[id='user_login']
o Css selector using multiple attribute:Syntax-tagname[attribute1='value1']
[attribute2='value2']
o Find css using id and class name. Syntax for id: tagname#id, syntax for class:
tagname.className
o Find css using contains. Syntax : tagname[attribute*=’value’]
o Find css using start-with. Syntax: tagname[attribute^=’value’]
o Find css using end-with. Syntax: tagname[attribute$=’value’]
Xpath Examples :
o Using multiple attribute. Syntax: //tagname[@attribute1=’value1’][attribute2=’value2’],
Example: //a[@id=’id1’][@name=’namevalue1’] , //img[@src=’’][@href=’’].
o Using single attribute. Syntax: // tagname[@attribute-name=’value1’] , Example: // a
[@href=’http://www.google.com’] , //input[@id=’name’] , //input[@name=’username’]
o Using contains method. Syntax: //tagname[contains(@attribute,’value1’)], Example:
//input[contains(@id,’’)] , //input[contains(@name,’’)] , //a[contains(@href,’’)] ,
//img[contains(@src,’’)] , //div[contains(@id,’’)]
o Using starts with. Syntax: //tagname[starts-with(@attribute-name,’’)] , Example: //id[starts-
with(@id,’’)]
o Using following node. Syntax: //input[@id=’’]/following::input[1]
o Using preceding node. Syntax: //input[@id=’’]/ preceding::input[1]
************************------------------******************
17- How to verify checkbox (any element) is enable/disabled/ checked/Unchecked/ displayed/ not
displayed?
Ans- We have different Boolean methods for enable / disable, checked / unchecked and displayed / not
displayed that are as follows:
1. There's a method "isEnabled()", that checks whether a WebElement is enabled or not. You
can use the below code to check for that;
boolean enabled = driver.findElement(By.xpath("//xpath of the checkbox")).isEnabled();
2. to check whether the checkbox is checked/selected or not, you can use "isSelected()"
method, which you can use like this;
boolean checked = driver.findElement(By.xpath("//xpath of the checkbox")).isSelected();
************************------------------******************
We can also deselect the item using same thing that is just above method like.
************************------------------******************
19- Have you worked with Web table (Calendar)? If yes, then what was your approach.
Ans- Yes. First need to analysis its web page html code for this element. To find which type of calendar
is, then you can decide you can solve this calendar by using selenium Webdriver or using JavaScript
executer. It all depends on the scenario the code. Now a day, there would be no. of new type of calendar
are using by dev teams. We can’t handle these by using selenium but using JavaScript executer we get
solution.
************************------------------******************
20- Can you tell me some navigation commands?
Ans- To access the navigation’s method, just type driver.navigate().. The intellisence feature of eclipse
will automatically display all the public methods of Navigate Interface.
Command - driver.navigate().to(appUrl);
It does exactly the same thing as the driver.get(appUrl) method. Where appUrl is the website address
to load. It is best to use a fully qualified URL.
forward() : void – This method does the same operation as clicking on the Forward Button of any
browser. It neither accepts nor returns anything.
Command - driver.navigate().forward();
Takes you forward by one page on the browser’s history.
back() : void – This method does the same operation as clicking on the Back Button of any browser. It
neither accepts nor returns anything.
Command - driver.navigate().back();
Takes youback by one page on the browser’s history.
refresh() : void – This method Refresh the current page. It neither accepts nor returns anything.
Command - driver.navigate().refresh();
Perform the same function as pressing F5 in the browser.
************************------------------******************
21- Difference between QUIT and Close?
Ans- driver.close and driver.quit are two different methods for closing the browser session in Selenium
WebDriver. Understanding both of them and knowing when to use which method is important in your test
execution. Therefore, in this article, we have tried to throw light on both these methods.
o driver.close – It closes the the browser window on which the focus is set.
o driver.quit – It basically calls driver.dispose method which in turn closes all the browser windows
and ends the WebDriver session gracefully.
You should use driver.quit whenever you want to end the program. It will close all opened browser
window and terminates the WebDriver session. If you do not use driver.quit at the end of program,
WebDriver session will not close properly and files would not be cleared off memory. This may result in
memory leak errors.
************************------------------******************
************************------------------******************
24- Can you explain implicit wait, explicit wait and fluent wait and what is the difference between all of
them? Which one you have used frequently?
Selenium WebDriver has borrowed the idea of implicit waits from Watir. This means that we can tell
Selenium that we would like it to wait for a certain amount of time before throwing an exception that it
cannot find the element on the page. We should note that implicit waits will be in place for the entire time
the browser is open. This means that any search for elements on the page could take the time the implicit
wait is set for.
Ex: WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://url_that_delays_loading");
Fluent Wait
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the
frequency with which to check the condition. Furthermore, the user may configure the wait to ignore
specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an
element on the page.
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
return driver.findElement(By.id("foo"));
});
Explicit Wait
It is more extendible in the means that you can set it up to wait for any condition you might like. Usually,
you can use some of the prebuilt ExpectedConditions to wait for elements to become clickable, visible,
invisible, etc.
Ex:
WebDriverWait wait = new WebDriverWait(driver, 10);
2
3 WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
Implicit Wait: During Implicit wait if the Web Driver cannot find it immediately because of its
availability, the WebDriver will wait for mentioned time and it will not try to find the element again
during the specified time period. Once the specified time is over, it will try to search the element once
again the last time before throwing exception. The default setting is zero. Once we set a time, the Web
Driver waits for the period of the WebDriver object instance.
Explicit Wait: There can be instance when a particular element takes more than a minute to load. In that
case you definitely not like to set a huge time to Implicit wait, as if you do this your browser will be going
to wait for the same time for every element.
To avoid that situation, you can simply put a separate time on the required element only. By following this
your browser implicit wait time would be short for every element and it would be large for specific
element.
Fluent Wait: Let’s say you have an element which sometime appears in just 1 second and some time it
takes minutes to appear. In that case it is better to use fluent wait, as this will try to find element again and
again until it finds it or until the final timer runs out.
************************------------------******************
25- What is JavaScript Executor and where you have used JavaScript executor?
Ans- JavascriptExecutor it is an interface. It Indicates that a driver can execute JavaScript, providing
access to the mechanism to do so.
There were lots of scenarios’ their we need java-script should be executing for some element that are as
follows:
1. when element is not clickable using locators then we can have used JavaScript.
2. While working with frames we used JavaScript.
3. The most recently while working with ck-editor I used JavaScript executers.
4. For the bootstrap calendar when the conditions for using selenium command it can’t be possible that
time I used JavaScript executer etc.
Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
************************------------------******************
26- How to capture Screenshot in Selenium? Can we capture screenshot only when test fails?
Ans- For taking screenshots Selenium has provided TakesScreenShot interface in this interface you can
use getScreenshotAs method which will capture the entire screenshot in form of file then using FileUtils
we can copy screenshots from one location to another location.
Ex: // Take screenshot and store as a file format
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile //method
FileUtils.copyFile(src, new File("C:/selenium/error.png"));
}
catch (IOException e)
{
System.out.println(e.getMessage());
And we can capture screen-shot while test fails we can do this by following way.
Ex: create one method for capturing screen-shot. And then call this method in test methods catch block.
catch (IOException e)
System.out.println(e.getMessage());
}
Now call this method in test methods catch block.
************************------------------******************
Why we are using Webdriver Listeners:If you talk about Webdriver we are doing some activity like
type, click, navigate etc this is all your events which you are performing on your script so we should have
activity which actually will keep track of it. Take an example if you perform click then what should
happen before click and after click. To capture these events, we will add listener that will perform this
task for us.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;
@Override
public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {
@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
@Override
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
@Override
public void afterNavigateBack(WebDriver arg0) {
@Override
public void afterNavigateForward(WebDriver arg0) {
@Override
public void afterNavigateTo(String arg0, WebDriver arg1) {
@Override
public void afterScript(String arg0, WebDriver arg1) {
@Override
public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {
@Override
public void beforeClickOn(WebElement arg0, WebDriver arg1) {
@Override
public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {
@Override
public void beforeNavigateBack(WebDriver arg0) {
@Override
public void beforeNavigateForward(WebDriver arg0) {
System.out.println("Before navigating Forword "+arg0.toString());
@Override
public void beforeNavigateTo(String arg0, WebDriver arg1) {
@Override
public void beforeScript(String arg0, WebDriver arg1) {
@Override
public void onException(Throwable arg0, WebDriver arg1) {
System.out.println("Testcase done"+arg0.toString());
System.out.println("Testcase done"+arg1.toString());
}
}
Let’s Discuss one of these methods
@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
In above method we are simply printing on console and this method will automatically called once click
events done. In same way you have to implement on methods.
Step 4- Now register that event using register method and pass the object of ActivityCapture class
event1.register(handle);
************************------------------******************
29- Can you write login script for Gmail or any other application?
Ans-Yes.
************************------------------******************
30- How to upload files in Selenium? Have you ever used AutoIT?
Ans-We can upload file in web application by using directly sending path in sendKeys. But at sometimes
selenium path could not accept or upload the things, for this we used AutoIT tool.
1-AutoIt is freeware automation tool that can work with desktop application too. 2-It uses a combination
of keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not
possible or reliable with other languages (e.g. VBScript and SendKeys).
************************------------------******************
DesiredCapabilities cap=DesiredCapabilities.internetExplorer();
DesiredCapabilities cap=DesiredCapabilities.safari();
************************------------------******************
The default Firefox profile is not very automation friendly. When you want to run automation reliably on
a Firefox browser it is advisable to make a separate profile. Automation profile should be light to load and
have special proxy and other settings to run good test.
You should be consistent with the profile you use on all development and test execution machines. If you
used different profiles everywhere, the SSL certificates you accepted or the plug-ins you installed would
be different and that would make the tests behave differently on the machines.
- There are several times when you need something special in your profile to make test execution
reliable. The most common example is a SSL certificate settings or browser plug-ins that handles self-
signed certs. It makes a lot of sense to create a profile that handles these special test needs and
packaging and deploying it along with the test execution code.
- You should use a very lightweight profile with just the settings and plug-ins you need for the
execution. Each time Selenium starts a new session driving a Firefox instance, it copies the entire
profile in some temporary directory and if the profile is big, it makes it, not only slow but unreliable as
well.
34- What are the issues or Challenges you faced while working with IE Browser?
Ans- Challenges with IE browser in selenium Webdriver.
Openqa.selenium.NoSuchWindowException. (This is a common issue with Selenium and you can
avoid this by doing some IE setting, which we are going to discuss now.)
sendKeys works very slow it takes 1 to 2 seconds to type each character. (This is a known issue
with Selenium and it only happens once you work with IE 64 bit driver.) Solution:You can
download IE Driver 32 bit and start using it, even you are working with 64 bit OS this 32 bit IE
driver works every time.
Unexpected error while launching Internet Explorer.Protected mode must be set to the same
value.( When I started working with IE this was the first exception, which I used to get, and I was
sure that this related to some browser setting.) We can solve this issue using do some setting in
internet explorer. To enabling one by one all security zones in internet options of IE.
Unexpected error launching Internet Explorer.Browser zoom level was set to 0%. (By the name
itself, you can see that we have to set the zoom level to 100 % to make it work.)
Handle Untrusted SSL certificate error in IE browser in different ways
Solution: IE is the product of Microsoft and IE is much worried about security so when you start
working with some https application you will get a untrusted certificate. Selenium has so many
ways to handle this, but we will see 2 ways which work all the time for me.
1. Open the application for which SSL certificate is coming so use below code after passing the
URL.
driver.get(“ur app URL”);
driver.navigate().to(“javascript:document.getElementById(‘overridelink’).click()”);
// you can use your code now. 2. You can
handle this certificate using Desired Capabilities as well. To accepting untrusted ssl certificates.
************************------------------******************
35- Have you ever faced any proxy issue if yes then how you handled?
Ans:
Handle proxy in Selenium Webdriver
When you try to access some secure applications you will get proxy issues so many times. Until we do
not set proxy, we cannot access the application itself.
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
p.setHttpProxy("localhost:7777");
cap.setCapability(CapabilityType.PROXY, p);
}
}
************************------------------******************
36- What is Actions class in Selenium (How to perform Mouse Hover, Keyboard events, DragAndDrop
etc?)
Ans-In Webdriver, handling keyboard events and mouse events (including actions such
as Drag and Drop or clicking multiple elements With Control key) are done using the
advanced user interactions API . It contains Actions and Action classes which are
needed when performing these events. For all advance activity in Selenium
Webdriver we can perform easily using Actions class like Drag and Drop,
mouse hover, right click, clickandhold, releasemouse many more.
We have predefined method called dragAndDrop(source, destination)
which is method of Actions class.
To use mouse actions, we need to use current location of the element and then perform
the action.The following are the regularly used mouse and keyboard events:
Method :clickAndHold()
Purpose: Clicks without releasing the current mouse location
Method : contentClick()
Purpose: Performs a context-click at the current mouse location.
How to work with context menu by taking a simple example
Method: doubleClick()
Purpose: Performs a double click at the current mouse location
Method: dragAndDrop(source,target)
Parameters: Source and Target
Purpose: Performs click and hold at the location of the source element and moves to the
location of the target element then releases the mouse.
Method : dragAndDropBy(source,x-offset,y-offset)
Parameters: Source, xOffset - horizontal move, y-Offset - vertical move Offset
Purpose: Performs click and hold at the location of the source element moves by a given
off set, then releases the mouse.
Method: keyDown(modifier_key)
Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONROL)
Purpose: Performs a modifier key press, doesn't release the modifier key. Subsequent
interactions may assume it's kept pressed
Method: keyUp(modifier_key)
Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONROL)
Purpose: Performs a key release.
Mouse Hover:
public class mouseHover{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.onlinestore.toolsqa.com");
action.moveToElement(element).build().perform();
driver.findElement(By.linkText("iPads")).click();
// Initiate browser
WebDriver driver=new FirefoxDriver();
// maximize browser
driver.manage().window().maximize();
// Open webpage
driver.get("http://jqueryui.com/resources/demos/droppable/default.html");
}
************************------------------******************
37- Do we have object repository concept in Selenium if yes then please explain how we can achieve it?
Whenever you talk about
Ans-Yes We have object Repository concept in selenium.
repository by the name itself you can think that it is kind of storage. Object
repository is the collection of object and object here is locator.
Here locator means web element id, name, CSS, XPath, class name etc.
Basically we can use object repository in automation framework because
we need to handle huge amount of element locator separate so that it easy
to handle and maintain.
************************------------------******************
// enter username
username.sendKeys("[email protected]");
}}
************************------------------******************
************************------------------******************
driver.manage().window().maximize();
driver.get("http://www.facebook.com");
}
************************------------------******************
41- What is log4j and How to generate log files in Selenium?
Ans- Log4j:Log4j is free open source tool given by Apache foundation for creating
log files It help us to generate log file in various output target.
Generate Log Files: In my automation framework I use these following steps.
Step1: Download log4j.jar and add into your project.
Step2. Then create log4j.xml. That are some available log4j files on internet.
Step3: We need to add Log.Java and then we can used logs in our automation framework that can we see
while running script in console and the above log4j.xml files create application.log file.
@Test
public void getTitlePage()
{
driver.get("https://www.salesforce.com/login");
driver.manage().window().maximize();
title = driver.getTitle();
driver.close();
}
}
Verify Tooltip:
public class Tooltip {
// It will compare if actual matches with expected then TC will fall else it will fail
Assert.assertEquals(tooltip_msg, expected_tooltip);
System.out.println("Message verifed");
// Open browser
FirefoxDriver driver=new FirefoxDriver();
// maximize browser
driver.manage().window().maximize();
// Open URL
driver.get("http://www.naukri.com/");
// Here Assert is a class and assertEquals is a method which will compare two values if// both matches
it will run fine but in case if does not match then if will throw an
//exception and fail testcases
}
}
************************------------------******************
setPreference("browser.download.folderList", 2);
Default Value: 1
The value of browser.download.folderList can be set to either 0, 1, or 2. When set to 0,
Firefox will save all files downloaded via the browser on the user's desktop. When set to
1, these downloads are stored in the Downloads folder. When set to 2, the location
specified for the most recent download is utilized again.
setPreference("browser.download.manager.showWhenStarting", false);
Default Value: true
The browser.download.manager.showWhenStarting Preference in Firefox's about:config
interface allows the user to specify whether or not the Download Manager window is
displayed when a file download is initiated.
browser.download.manager.alertOnEXEOpen
True (default): warn the user attempting to open an executable from the Download
Manager
False: display no warning and allow executable to be run
Note: In Firefox, this can be changed by checking the "Don't ask me this again" box
when you encounter the alert.browser. download. manager. closeWhenDone
True: Close the Download Manager when all downloads are complete
False (default): Opposite of the above
************************------------------******************
45- Have you integrated Selenium with other tools like Sikuli, Ant, Maven, and Jenkins? If yes, then how
you have used them?
Ans- Yes I am very much interested. Currently I am using Ant in my automation framework. And I am
planning to use maven in next project. But individually I have performed some demo on Sikuli, maven,
Jenkins as well.
************************------------------******************
1. It does not support and non-web-based applications, it only supports web based applications.
2. You need to know at least one of the supported language very well in order to automate your
application successfully.
3. No inbuilt reporting capability so you need plugins like JUnit and TestNG for test reports.
4. Lot of challenges with IE browser.
************************------------------******************
How we create POC for current project/ application?Why POC is important for Automation testing?What
is POC in Automation? A POC stands for Proof of Concept. It is just a document or
some time a demo piece of code, which describe points, and some questions/answer. In Other
words- It simply words that we have to proof that what are doing and what will be outcome of the same.
Example- When we are running automation script for some testcase what will be
total saving or effort you have saved via automation and so on.
How we create POC for current project/ application? While creating POC
documents/dem you should be ready with some Points.
2. For each tool, create a simple automation script for desired testing tasks and compare the result,
pros and cons.
3. When you have the automation-working fine then you can present it to your manager, lead, or
client for next action. If they agree then you can adapt the same
POC document is very important for companies before moving to automation like why they should move
to manual to automation. What will be saving- Effort saving/ Time saving/Money saving etc. Because
automation tools require kind of programming knowledge. POC document will give result that whether
we should move from Manual to Automation for the fowling project or not.
************************------------------******************
Now its time for execution of test scripts, in this phas you have to execute all your test script.
************************------------------******************
50- What is Automation Test Plan?
Ans-
Does the company already have licenses for a certain tool, try and see if you can use it?
Look for open source (but reliable) tools
Do the team members know the tool already or do we need to bring in someone new? Or train the
existing ones?
Section #5: Schedules
************************------------------******************
Selenium Webdriver/RC/IDE Interview questions and Answers
All these question that we discussed now that is the combination of all level (Beginner, Advance).
They will definitely ask so many questions from Framework itself and they will try to drag you in this
topics because most of the people will stuck and interviewer will get to know that person has actually
worked on Selenium or not.
Please make sure you are giving proper answer
52- Have you designed framework in your team or you are using existing framework, which already
implemented by other members?
Ans-Yes. I have implemented and created framework in my team.
************************------------------******************
55- Can you create one sample script using your framework?
Ans- No. Because it needs to take time to make framework. And at same time I did not know all the
things but I can.
************************------------------******************
There is again no limitation or specific question so be ready with any type of question but make sure
whenever you are giving answer it should have valid point or you can directly say that I am not sure about
it.
56- What is TestNG?Ans: TestNG is a testing framework inspired from JUnit and NUnit, but introducing
some new functionalities that make it more powerful and easier to use.
TestNG is an open source automated testing framework; where NG means Next Generation. TestNG is
similar to JUnit (especially JUnit 4),
but it is not a JUnit extension. It is inspired by JUnit. It is designed to be better than JUnit, especially
when testing integrated classes.
2. Supports testing integrated classes (e.g., by default, no need to create a new test class instance for every
test method).
5. Introduces ‘test groups’. Once you have compiled your tests, you can just ask TestNG to run all the
"front-end" tests, or "fast", "slow", "database" tests, etc.
6. Supports Dependent test methods, parallel testing, load testing, and partial failure.
57- Why you have used TestNG in your framework? Can you compare JUNIT with TestNG framework?
Ans: Difference between testng and junit.
The sequence of actions is regulated by easy-to-understand annotations that do not require methods to be
static.
5. Uncaught exceptions are automatically handled by TestNG without terminating the test prematurely.
These exceptions are reported as failed steps in the report.TestNG fares better than JUnit on following
parameters.
Both the frameworks have support for annotations. In JUnit 4, the @BeforeClass and @AfterClass
TestNG does not have this constraint. TestNG has provided three additional setup/teardown pairs
for the suite, test and groups, i.e. @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest,
2) Dependent Tests
@Test
@Test(dependsOnMethods={“test1”})
System.out.println(“This is test2”);
}
The “test2()” will execute only if “test1()” is run successfully, else “test2()” will skip the test.
JUnit does not have inherent support for parallel execution. However, we can use maven-
surefire-plugin and Gradle test task attribute maxParallelForks to execute the tests in
parallel. TestNG has inherent support for parallelization by means of “parallel” and “thread-count”
attributes in . @Test annotation has threadPoolSize attribute.JUnit is often shipped with mainstream IDEs
by default, which contributes to its wider
popularity. However, TestNG’s goal is much wider, which includes not only unit testing, but also support
of integration and acceptance testing, etc. Which one is better or more suitable depends on use contexts
and requirements.
4) In TestNG, Parameterized test configuration is very easy while It is very hard to configure
Annotation Description
@AfterTest The annotated method will be run after all the test
methods belonging to the classes inside the <test>
tag have run.
59- What is priority feature in TestNG? In addition, how we can use this?
Ans:
1. In TestNG "Priority" is used to schedule the test cases. When there are multiple test cases, we
want to execute test cases in order.
2. In order to achive, we use need to add annotation as @Test(priority=??). The default value will be
zero for priority.
3. If we define priority as "priority=", these test cases will get executed only when all the test cases
which don't have any priority as the default priority will be set to "priority=0".
Eg. The below examples shows using the priority for test cases.
@Test
public void registerAccount(){
@Test(priority=2)
public void sendEmail(){ System.out.println("Send email
after login"); }
@Test(priority=1)
public void
login(){ System.out.println("Login to the account after
registration");}}
************************------------------*****************
Code:
Code:
The preceding test class contains two test methods which print a message name onto the console when
executed. Here, test method testOne depends on test method testTwo. This is configured by using the
attribute dependsOnMethods while using the Test annotation.
************************------------------*****************
Example:
We need to specify the class names along with packages in between the classes tags. In the above xml, we
have specified class name as “com.first.example.demoOne” and “com.first.example.demoOne” which are
in “com.first.example” package. And class name demoThree is in package “com.second.example.” All the
classes specified in the xml will get executes which have TestNG annotations. Below are the two example
classes under “com.first.example” package which is executed.
public class demoOne { @Test public void
firstTestCase(){ System.out.println("im in first test
case from demoOne Class"); }
@Test
public void secondTestCase(){
System.out.println("im in second test case from demoOne Class");}}
We need to run the testng.xml file. (Right click on testng.xml and select Run as ‘TestNG Suite”)
************************------------------*****************
Code:
The below is the XML file to execute, the test methods with group. We will execute the group
“Regression” which will execute the test methods which are defined with group as “Regression”
<?xml version="1.0" encoding="UTF-8"?> <suite
name="Sample Suite"> <test name="testing">
<groups>
<run>
<include name="Regression"/> </run>
</groups>
<classes><class name="com.example.group.groupExamples" /></classes></test></suite>
************************------------------*****************
63- How to execute multiple test cases in Selenium?
Ans: TestNG provides an option to execute multiple tests in a single configuration file (testng.xml). It
allows to divide tests into different parts and group them in a single tests. We can group all the tests
related to database into one group, Regression tests in one group. And all the test cases related to Unit test
cases into one group and so on. In testng.xml file we can specify multiple name (s) which needs to be
executed. In a project there may be many classes, but we want to execute only the selected classes. We
can pass class names of multiple packages also. If say suppose, we want to execute two classes in one
package and other class from some other package.Code:
The below is the simple testng.xml file, if you observe, we are defining two attributes 'parallel' and
'thread-count' at suite level. As we want test methods to be executed in parallel, we have provided
'methods'. And 'thread-count' attribute is to use to pass the number of maximum threads to be created.
</suite>************************------------------*****************
IExecutionListener
IAnnotationTransformer
ISuiteListener
ITestListener
IConfigurationListener
IMethodInterceptor
IInvokedMethodListener
IHookable
IReporter
************************------------------*****************
66- What is Data provider in TestNG?
Ans-An important features provided by TestNG is the DataProvider
feature. It helps you to write data-driven tests, which essentially
means that same test method can be run multiple times with
different data-sets. Please note that DataProvider is the second
way of passing parameters to test methods (first way we already
discussed in @Parameters example). It helps in providing complex
parameters to the test methods as it is not possible to do this
from XML.
To use the DataProvider feature in your tests you have to declare
a method annotated by @DataProvider and then use the said method
in the test method using the ‘dataProvider‘ attribute in the Test
annotation.
publicclassSameClassDataProvider
{
@DataProvider(name = "data-provider")
publicObject[][] dataProviderMethod() {
returnnewObject[][] { { "data one"}, { "data two"} };
}
@Test(dataProvider = "data-provider")
publicvoidtestMethod(String data) {
System.out.println("Data is: "+ data);
}
}
Now run above test. Output of above test run is given below:
Data is: data one
Data is: data two
PASSED: testMethod("data one")
2) Using @DataProvider
PASSED: testMethod("data two")
DataProvider.java
publicclassDataProviderClass
{
@DataProvider(name = "data-provider")
publicstaticObject[][] dataProviderMethod()
{
returnnewObject[][] { { "data one"}, { "data two"} };
}
}
TestClass.java
importorg.testng.annotations.Test;
publicclassTestClass
{
@Test(dataProvider = "data-provider", dataProviderClass =
DataProviderClass.class)
publicvoidtestMethod(String data)
{
System.out.println("Data is: "+ data);
}
}
Now run above test. Output of above test run is given below:
Data is: data one
Data is: data two
PASSED: testMethod("data one")
PASSED: testMethod("data two")
************************------------------*****************
67- How to disable particular test case?
Ans-Just add an attribute enabled=false in test declaration annotation.
Ex: @Test(enabled=false)
************************------------------*****************
68- How to generate reports in TestNG?
Ans- We just need to run an annotated TestNG annotation scripts and refresh the project you can see the
test-output folder is generated in project explorer. Just click on to it, and then click on to the emailable-
report.html you can view the testNG report in HTML format
************************------------------*****************
@Test
public void testReport(){
Reporter.log("Browser Opened");
driver.manage().window().maximize();
Reporter.log("Browser Maximized");
driver.get("http://www.google.com");
Reporter.log("Application started");
driver.quit();
Reporter.log("Application closed");
************************------------------*****************
70- How to execute only failed test cases in Selenium?
Ans-We can achieve this thing by using IRetryAnalyer Interface.
Code:
// implement IRetryAnalyzer interface
// set counter to 0
int minretryCount=0;
int maxretryCount=2;
// this will run until max count completes if test pass within this frame it will come out of
for loop
if(minretryCount<=maxretryCount)
minretryCount++;
return true;
return false;
}
}
Now we are done almost only we need to specify this in the test case.
@Test(retryAnalyzer=Retry.class)
In above statement, we are giving instruction to our test case that if the
test case fails then it will call Retry class that we created above.
************************------------------*****************
Now if an interviewer having good knowledge on Selenium and have worked on different tools then be
ready with other question too that will be related to Selenium only.
We have so many tools in market that we can integrate with Selenium like Maven, Sikuli, Jenkins,
AutoIT, Ant and so on.
I will try to summarize question-based on the tools, which I have used.
Maven
71- Can you please explain what is apache maven and Apache ant?
Ans- Apache Maven:Apache Maven is a software project management and
comprehension tool. Based on the concept of a project object model (POM),
Maven can manage a project's build, reporting and documentation from a central
piece of information.
Apache Ant:Apache Ant is a Java library and command-line tool whose mission is to drive
processes described in build files as targets and extension points dependent upon each other.
The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in
tasks allowing to compile, assemble, test and run Java applications. Ant can also be used
effectively to build non Java applications, for instance C or C++ applications. More generally, Ant
can be used to pilot any type of process which can be described in terms of targets and tasks.
************************------------------*****************
72- Do you have used Maven project in your organization? If yes, then have you created build to execute
your test?
Ans- No I don’t create maven project for company. But I have created demo for it.
************************------------------*****************
75- Can you please explain Maven life cycle?
Ans-
************************------------------*****************
Sikuli
76- Have you heard of Sikuli? If yes, can you please explain what exactly Sikuli does?
Ans: Sikuli automates anything you see on the screen. It uses image recognition to identify and control
GUI components. It is useful when there is no easy access to a GUI's internal or source code.
************************------------------*****************
78- Advantage of Sikuli, Limitation of Sikuli.
Ans- 1. Sikuli is open source. 2.
Sikuli IDE gives enough API's to interact with desktop based applications. Adding on to that we can use
most of the API's of python scripting as well. Which totally depends upon how we code basically.
3. Image/Picture recognition in case of Sikuli is pretty much accurate. If we want more accuracy, we have
to specify the regions of the images on the screen properly (This solves the problem of identification of
small images on the screen). 4. Pretty much useful if
the application demands so much of interaction from the user. 5. Behavior part
of an application can be effectively analyzed. 6. We can
easily identify the application crashes and bugs if we write script efficiently. 7.
We can easily perform Boundary values testing of an application, which again depends on the scripting.
8. One of the biggest advantage of Sikuli is that, it can easily automate Flash objects.
9. makes easy to automate windows application.
Cons: 1. Running of
batch wise sikuli scrips is little tricky and will not work some times in case we have 10 sikuli scripts and
if we want to run them one by one automatically. 2. sikuli IDE
hangs often and some time doesnt even gets opened untill we clear the registry. 3.
sikuli is resolution dependent. (Which means the script written in 1366 * 768 screen resolution might not
work in other resolutions).
************************------------------*****************
79- How to integrate Sikuli with Selenium script?
Ans-Step #1: Create a new Java Project in eclipse by clicking New -> Java project.Step #2:Right click on
the Project Go to Build Path -> Configure Build Path.Switch to Libraries Tab. Click on “Add External
Jars” and Add Selenium library jars as well as Sikuli-scritp.jarStep #3:Create a package inside src/ folder
and create a class under that package.Eg.
import org.junit.Test; import
org.openqa.selenium.WebDriver;import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.App;import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;import org.sikuli.script.Screen;
************************------------------*****************
80- Can you tell us the scenario where you have used Sikuli with Selenium?
Ans- 1) Here the scenario is to identify the “I’m Feeling Lucky” button and to click it using Sikuli.
Open Google home page from your browser and Capture “I’m Feeling Lucky” button using any screen
capturing tool and save it to your local machine.
Note: Please don’t change the image by highlighting it or by editing. If you do so, then Sikuli may throw
an error like “Can’t find image on the screen”.
************************------------------*****************
Jenkins
This is very vast topic and very interested but as an automation tester you will use it based on requirement
81- What is CI (Continuous integration) and what are different tools available in market.
Ans-Continuous Integration (CI) is a development practice that requires developers
to integrate code into a shared repository several times a day. Each check-in is then
verified by an automated build, allowing teams to detect problems early.
************************------------------*****************
82- How to integrate Jenkins with Selenium?
Ans-1. Open your web browser and then Navigate to Below URL http://jenkins-ci.org this is the official
website of Jenkins.
2. Now download Jenkins.war file and save it. 3. Go to location where
Jenkins.war is available. 4. Step 2-
Open Command prompt knows as CMD and navigate till project home directory and Start Jenkins server
Start- cmd> Project_home_Directory> java -jar jenkins.war 5.
Open any browser and type the url http://localhost:8080
6. Click on > Manage Jenkins
7. Click on Configure System, Navigate to JDK section and Click on Add JDK button, Uncheck Install
automatically check box so Jenkins will only take java which we have mention above.
8. Give the name as JAVA_HOME and Specify the JDK path
9. Part 3- Execute Selenium build using Jenkins
10.Part 4-Schedule your build in Jenkins for periodic execution
************************------------------*****************
Ans-Open Task Scheduler by clicking the Start button Picture of the Start button, clicking Control Panel,
clicking System and Security, clicking Administrative Tools, and then double-clicking Task Scheduler.
Administrator permission required If you're prompted for an administrator password or confirmation, type
the password or provide confirmation.
o Click the Action menu, and then click Create Basic Task.
o Type a name for the task and an optional description, and then click Next.
o To select a schedule based on the calendar, click Daily, Weekly, Monthly, or One time, click Next;
specify the schedule you want to use, and then click Next.
o To select a schedule based on common recurring events, click When the computer starts or When
I log on, and then click Next.
o To select a schedule based on specific events, click When a specific event is logged, click Next;
specify the event log and other information using the drop-down lists, and then click Next.
o To schedule a program to start automatically, click Start a program, and then click Next.
o Click Browse to find the program you want to start, and then click Next.
o Click Finish.
************************------------------*****************
84- Can you send email through Jenkins?
Ans- Yes.
Enter valid email address to “System Admin e-mail address”“Extended E-mail Notification”
section
Click “Advanced”
Click “Use SMTP Authentication”
Click “Always”
Save
Test-run
************************------------------*****************
Ans-A "master" operating by itself is the basic installation of Jenkins and in this configuration the master
handles all tasks for your build system. In most cases installing a slave doesn't change the behavior of the
master. It will serve all HTTP requests, and it can still build projects on its own. Once you install a few
slaves you might find yourself removing the executors on the master in order to free up master resources
(allowing it to concentrate resources on managing your build environment) but this is not a necessary
step. If you start to use Jenkins a lot with just a master you will most likely find that you will run out of
resources (memory, CPU, etc.). At this point you can either upgrade your master or you can setup slaves
to pick up the load. As mentioned above you might also need several different environments to test your
builds. In this case using a slave to represent each of your required environments is almost a must.
A slave is a computer that is set up to offload build projects from the master and once setup this
distribution of tasks is fairly automatic. The exact delegation behavior depends on the configuration of
each project; some projects may choose to "stick" to a particular machine for a build, while others may
choose to roam freely between slaves. For people accessing your Jenkins system via the integrated
website (http://yourjenkinsmaster:8080), things work mostly transparently. You can still browse javadoc,
see test results, download build results from a master, without ever noticing that builds were done by
slaves. In other words, the master becomes a sort of "portal" to the entire build farm. Since each slave
runs a separate program called a "slave agent" there is no need to install the full Jenkins (package or
compiled binaries) on a slave. There are various ways to start slave agents, but in the end the slave agent
and Jenkins master needs to establish a bi-directional communication link (for example a TCP/IP socket.)
in order to operate.
************************------------------*****************
Random Questions
86- What is robot class and where have we used this in Selenium?
Ans- robot class is a class of java programming. It uses to facilitate automated testing of java platform
implementations. It provides no. of methods to fire windows keyboard and mouse events. Syntax and
example are as follows:
Some commonly and popular used methods of Robot API during web automation:
In certain Selenium Automation Tests, there is a need to control keyboard or mouse to interact with OS
windows like Download pop-up, Alerts, Print Pop-ups, etc. or native Operation System applications like
Notepad, Skype, Calculator, etc. Selenium Webdriver cannot handle these OS pop-ups/applications.
************************------------------*****************
87- Be ready with some basic Java programs which every automation Engg should know
Like string reverse, count the number of characters in a given string and so on.
If you will apply for Amazon, Flipkart then make sure you know Data structure very well because
question level will be very high.
************************------------------*****************
88- List down all locator with performance.
Ans-As per performance of locator from top to bottom.
Linktext - >Select link (anchor tag) element which contains text matching the specified link text
Partial Linktext - >Select link (anchor tag) element which contains text matching the specified partial link
text
Css - >Select the element using css selectors. You can check here for Css examples and You can also
refer W3C CSS Locatros
************************------------------*****************
89- Find broken links on Web page.
Ans: Scenario for find broken links using selenium
Before jumping to the code let’s take one simple example to get the actual concept.
Example1- Suppose we have one application which contains 400 links and we need to verify the link is
broken or not.
Program for finding broken links
driver.manage().window().maximize();
driver.get("http://www.google.co.in/");
List<WebElement> links=driver.findElements(By.tagName("a"));
for(int i=0;i<links.size();i++)
String url=ele.getAttribute("href");
verifyLinkActive(url);
try
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==200)
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
}
if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)
}catch(Exception e){}}}
************************------------------*****************
90- How to read write excel files using Apache POI.
Ans: Basics of APACHE POI
There are two main prefixes which you will encounter when working with Apache POI:
HSSF: denotes the API is for working with Excel 2003 and earlier.
XSSF: denotes the API is for working with Excel 2007 and later.
And to get started the Apache POI API, you just need to understand and use the following 4 interfaces:
Workbook: high level representation of an Excel workbook. Concrete implementations
are: HSSFWorkbook andXSSFWorkbook.
Sheet: high level representation of an Excel worksheet. Typical implementing classes
are HSSFSheet and XSSFSheet.
Row: high level representation of a row in a spreadsheet. HSSFRow and XSSFRow are two
concrete classes.
Cell: high level representation of a cell in a row. HSSFCell and XSSFCell are the typical
implementing classes.
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
************************------------------*****************
91- Have you ever done connection with Database using JDBC?
Ans-Yes.Used MySQL as database.
************************------------------*****************
92- Read CSV files.
Ans-Program to read csv file.
package blog;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
String[] str=i1.next();
for(int i=0;i<str.length;i++)
{
System.out.print(" "+str[i]);
}
System.out.println(" ");
}
************************------------------*****************
93- How to read properties files in Selenium?
Ans- Program for reading properties file.
public class ReadFileData {
public static void main(String[] args) {
File file = new File("D:/Dev/ReadData/src/datafile.properties");
FileInputStream fileInput = null; try
{
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) { e.printStackTrace(); }
Properties prop = new Properties(); //load properties file try
{
prop.load(fileInput);
} catch (IOException e) { e.printStackTrace(); }
WebDriver driver = new FirefoxDriver();
driver.get(prop.getProperty("URL"));
driver.findElement(By.id("Email")).sendKeys(prop.getProperty("username"));
driver.findElement(By.id("Passwd")).sendKeys(prop.getProperty("password"));
driver.findElement(By.id("SignIn")).click();
System.out.println("URL ::" + prop.getProperty("URL")); System.out.println("User name::"
+prop.getProperty("username"));
System.out.println("Password::" +prop.getProperty("password"));
}}
The below is the Output after executing the program: We are passing the properties values to the
webdriver and printing the values at end
URL::http://gmail.com
Username::testuser
Password::password123
************************------------------*****************
94- Does Selenium support mobile automation?
Ans-using Appium or other automation tool (need to confirm more on it.)
************************------------------*****************
95- What is Selendroid?
Ans-Selendroid can be used to test already built apps. Those Android apps (apk file) must exist on the
machine, where theselendroid-standalone server will be started. The reason for this is that a
customized selendroid-server for the app under test (AUT) will be created. Both apps (selendroid-server
and AUT) must be signed with the same certificate in order to install the apks on the device.
************************------------------*****************
96- What is Appium?
Ans- Appium aims to automate any mobile app from any language and any test framework, with full
access to back-end APIs and DBs from test code. Write tests with your favorite dev tools using all the
above programming languages, and probably more (with the Selenium WebDriver API and language-
specific client libraries).
************************------------------*****************
97- What is same origin policy in Selenium?
Ans-First of all “Same Origin Policy” is introduced for security reason, and it ensures that content of
your site will never be accessible by a script from another site. As per the policy, any code loaded within
the browser can only operate within that website’s domain.
Same Origin policy prohibits JavaScript code from accessing elements from a domain that is different
from where it was launched. Example, the HTML code in www.google.com uses a JavaScript
program "testScript.js". The same origin policy will only allow testScript.js to access pages
withingoogle.com such as google.com/mail, google.com/login, or google.com/signup. However, it
cannot access pages from different sites such as yahoo.com/search or fbk.com because they belong to
different domains.
To avoid “Same Origin Policy” proxy injection method is used, in proxy injection mode the Selenium
Server acts as a client configured HTTP proxy , which sits between the browser and application under
test and then masks the AUT under a fictional URL
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. This security
restriction is of utmost important but spoils the working of Selenium. This is where Selenium server
comes to play an important role.
************************------------------*****************
98- What is Selenium grid, hub, node and commands that used in Selenium Grid?
Ans- Selenium Grid:Selenium Grid is a tool that distributes the tests across multiple physical or virtual
machines so that we can execute scripts in parallel (simultaneously). It dramatically accelerates the testing
process across browsers and across platforms by giving us quick and accurate feedback.
Hub: The hub can also be understood as a server which acts as the central point where the tests would be
triggered. A Selenium Grid has only one Hub and it is launched on a single machine once.
Node: Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can
be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported
browsers.
************************------------------*****************
99-What is the difference between / and // in XPATH?Ans- “/” It’s starts search selection from root
element in document. (absolute path)
“//” It start selection from anywhere in XML document. (relative path)
************************------------------*****************
100- Can we automate Flash application in Selenium?
Ans-The straightforward answer to it is that Selenium has no interface to interact with your Flash content.
Flash files are programmed in ActionScript and are very similar to JavaScript. Flash files also contains
programming Elements just like other languages. For e.g. they too have buttons, text box etc. Interacting
with these elements cause the Flash file to call some internal methods to do the task.
It’s a fairly simple process. All you have to do is use the ExternalInterface class. We will start it with a
small example. This is a small flash application which contains 3 buttons. Add, Subtract and Multiply.
These three buttons when clicked sends a text to a Text control and write down what the name of the
button is. So if you click Add you will find text “Add” being added to the Text
control.************************------------------*****************