Selenium WebDriver
Selenium WebDriver
Part 1
JUnit
TestNG
You can find TestNG Tutorials links on THIS PAGE.
11: Can you tell me the syntax to open/launch Firefox browser In WebDriver
software testing tool?
Answer: We can open new Mozilla Firefox browser Instance using bellow given
syntax In WebDriver software testing tool.
WebDriver driver = new FirefoxDriver();
13: Which tool you are using to find the XPath of any element?
Answer: I am using Mozilla Firefox AddOns FireBug and FirePath to find the
XPath of software web elements. See THIS POST to download it.
14: What is the difference between absolute XPath and relative XPath?
Answer:
Absolute XPath: Absolute XPath Is the full path starting from root node and ends
with desired descendant element's node. It will start using single forward slash(/)
as bellow.
Example Of Absolute XPath:
/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]
/div/div/div/div[1]/div/div/div/div[1]/div[2]/form/table/tbody/tr[1]/td/input
Above XPath Is absolute XPath of calc result box given on THIS PAGE. It
starts top node html and ends with input node.
Relative XPath: Instead of starting from root node, Relative XPath starts from
any In between node or current element's node(last node of element). It will start
using double forward slash(//) as bellow.
//input[@id='Resultbox']
Above XPath Is relative XPath of same calc result box given on THIS PAGE.
Alternative 1: Look for any other attribute which is not changing every time In
that div node like name, class etc. So if this div node has class attribute then we
can write xpath as bellow.
//div[@class='post-body entry-content']/div[1]/form[1]/input[1]
Alternative 2: You can use absolute xpath(full xpath) where you not need to give
any attribute names In xpath.
/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]
/div/div/div/div[1]/div/div/div/div[1]/div[2]/div[1]/form[1]/input[1]
Alternative 3: Use starts-with function. In this xpath's ID attribute, "post-body-"
part remain same every time. So you can use xpath as bellow.
//div[starts-with(@id,'post-body-')]/div[1]/form[1]/input[1]
Alternative 4: Use contains function. Same way you can use contains function
as bellow.
div[contains(@id,'post-body-')]/div[1]/form[1]/input[1]
16: How to press ENTER key button on text box In selenium webdriver?
Answer: To press ENTER key using selenium WebDriver software automation
tool, We need to use selenium Enum Keys with Its constant ENTER as bellow.
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys(Keys.ENTER);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
If you will write above syntax in your test, Your WebDriver test will wait 10
seconds for appearing element on page.
Above code will wait for 20 seconds for targeted element to be displayed and
enabled or we can say clickable.
20: I wants to pause my test execution for fix 10 seconds at specific point.
How can I do it?
Answer: You can use java.lang.Thread.sleep(long milliseconds) method to
pause the software test execution for specific time. If you wants to pause your test
execution for 10 seconds then you can use bellow given syntax in your test.
Thread.sleep(10000);
21: How does selenium RC software testing tool drive the browser?
Answer:
When browser loaded In Selenium RC, It ‘injected’ javascript functions into the
browser and then It Is using javascript to drive the browser for software
application under test.
22: How does the selenium WebDriver drive the browser?
Answer: Selenium webdriver software testing tool works like real user
interacting with software web page and its elements. It is using each browser's
native support to make direct calls with browser for your software application
under test. There is not any Intermediate thing in selenium webdriver to Interact
with web browsers.
23: Do you need Selenium Server to run your tests In selenium WebDriver?
Answer: It depends. If you are using only selenium webdriver API to run your
tests and you are running your all your tests on same machine then you do not
need selenium server because In this case, webdriver can directly Interact with
browser using browser's native support.
You need selenium server with webdriver when you have to perform bellow given
operations with selenium webdriver.
When you are using remote or virtual machine to run webdriver tests for
software web application and that machine have specific browser version that is
not on your current machine.
When you are using selenium-grid to distribute your webdriver's test
execution on different remote or virtual machines.
24: Bellow given syntax will work to navigate to specified URL In
WebDriver? Why?
driver.get("www.google.com");
Answer : No. It will not work and show you an exception like: "Exception in
thread "main" org.openqa.selenium.WebDriverException: f.QueryInterface is not
a function" when you run your test.
You need to provide http:// protocol with URL In driver.get method as bellow.
driver.get("http://www.google.com");
25: Tell me a reason behind bellow given WebDriver exception and how will
you resolve It?
"Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Unable to locate element"
Answer: You will get this exception when WebDriver Is not able to locate
element on the page of software web application using whatever locator you have
used In your test. To resolved this Issue, I will check bellow given things.
First of all I will check that I have placed Implicit wait code In my test or
not. If you have not placed Implicit timeout In your test and any element Is taking
some time to appear on page then you can get this exception. So I will add bellow
given line at beginning of my test case code to wait for 15 seconds for element to
be present on page. In 70% cases, this step will resolved Issue. View Practical
Example Of Implicit Wait.
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
27: Can you tell me the alternative driver.get() method to open URL In
browser?
Answer: We can use anyone from bellow given two methods to open URL In
web browser in selenium webdriver software testing tool.
1. driver.get()
2. driver.navigate().to()
28: Can you tell me a difference between driver.get() and driver.navigate()
methods?
Answer: Main and mostly used functions of both methods are as bellow.
driver.get()
driver.get() method is generally used for Open URL of software web
application.
It will wait till the whole page gets loaded.
driver.navigate()
driver.navigate() method is generally used for navigate to URL of
software web application, navigate back, navigate forward, refresh the page.
It will just navigate to the page but wait not wait till the whole page gets
loaded.
View more detailed description with example.
29: WebDriver has built In Object Repository. Correct me if I am wrong.
Answer: No. WebDriver do not have any built in object repository till now. But
yes, I am using java .properties file in my framework to store all required
element objects in my tests. View Example.
30: Can you tell me syntax to set browser window size to 800(Width) X
600(Height)?
Answer: We can set browser window size using setSize method of selenium
webdriver software testing tool. To set size at 800 X 600, Use bellow given
syntax in your test case.
driver.manage().window().setSize(new Dimension(500,500));
31: Can you tell me the names of different projects of selenium software
automation testing tool?
Answer: At present, Selenium software automation testing tool has four different
projects as bellow.
Selenium IDE: It Is Firefox add-on which allows you to record and
playback your software web application's tests In Firefox browser.
Selenium RC: It is software web application automation tool which allows
you to write your tests in many different programming languages.
Selenium WebDriver: It is well designed object oriented API developed
to automate web and mobile software application testing process. You can write
your tests in different languages too in selenium webdriver.
Selenium Grid: Grid allows you to execute your tests in parallel by
distributing them on different machines having different browser/OS
combinations.
32: I wants to use java language to create tests with Selenium WebDriver.
Can you tell me how to get latest version of WebDriver?
Answer: You can download language specific latest released client drivers for
selenium WebDriver software testing tool at http://docs.seleniumhq.org official
website. For java language, you will get bunch of jar files in zip folder. And then
you can add all those jar files in your project's java build path as a referenced
libraries to get support of webdriver API.
33: Can you tell me the usage of "submit" method in selenium WebDriver?
Answer: We can use submit method to submit the forms in selenium WebDriver
software automation testing tool. Example: Submitting registration form,
submitting Login form, submitting Contact Us form ect.. After filling all required
fields, we can call submit method to submit the form. VIEW EXAMPLE.
34: Do you have faced any Issue with "submit" method any time?
Answer: Yes, I have faced Issue like submit method was not working to submit
the form. In this case, Submit button of form was located outside the opening
<form> and closing </form> tags. In this case submit method will not works to
submit the form.
Also If submit button is located Inside opening <form> and closing </form> tags
but that button's type tag's attribute isn’t submit then submit method will not
work. It (type tag's attribute) should be always submit.
35: What is the syntax to type value in prompt dialog box's Input field using
selenium WebDriver?
Answer: Prompt dialog is just like confirmation alert dialog but with option of
Input text box as bellow.
To Input value in that text box of prompt dialog, you can use bellow given syntax.
driver.switchTo().alert().sendKeys("Jhon");
36: When I am running software web application's tests In Firefox Browser
using selenium webdriver, It Is not showing me any bookmarks, add-ons,
saved passwords etc. In that browser. Do you know why?
Answer: Yes. It Is because all those bookmarks, add-ons, passwords etc.. are
saved in your regular browser's profile folder so when you launch browser
manually, It will use existing profile settings so it will show you all those stuffs.
But when you run your software web application's tests in selenium webdriver, It
Is opening new browser Instance with blank/new profile. So it will not show you
bookmarks and all those things in that browser Instance.
You can create custom firefox profile and then you can use It In selenium
webdriver test. In your custom profile, you can set all required bookmarks, add-
ons etc.. VIEW THIS EXAMPLE to know how to set custom profile of firefox
browser.
37: Arrange bellow given drivers in fastest to slowest sequence?
Firefox Driver, HtmlUnit Driver, Internet Explorer Driver.
Answer: HTMLUnit Driver Is faster than all other drivers because It Is not using
any UI to execute test cases of software web application. Internet Explorer driver
is slower than Firefox and HtmlUnit driver. So, Fastest to slowest driver sequence
is as bellow.
1. HtmlUnit Driver
2. Firefox Driver
3. Internet Explorer Driver
38: What Is Ajax?
Answer: Asynchronous JavaScript and XML Is full form of AJAX which Is
used for creating dynamic web pages very fast for software web applications.
Using ajax, we can update page behind the scene by exchanging small amounts
of data with server asynchronously. That means, using ajax we can update page
data without reloading page.
39: How to handle Ajax In selenium WebDriver?
Answer: Generally we are using Implicit wait in selenium WebDriver software
automation tests to wait for some element to be present on page. But Ajax call
can not be handled using only Implicit wait In your test because page not get
reloaded when ajax call sent and received from server and we can not assume
how much time It will take to receive ajax call from server.
40: On Google search page, I wants to search for some words without
clicking on Google Search button. Is It possible In WebDriver? How?
Answer: Yes we can do it using WebDriver sendKeys method where we do not
need to use Google Search button. Syntax is as bellow.
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys("Search
Syntax",Keys.ENTER);
42: Give me any five different xPath syntax to locate bellow given Input
element.
<input id="fk-top-search-box" class="search-bar-text fk-font-13 ac_input"
type="text" autofocus="autofocus" value="" name="q" />
Answer: Five xPath syntax for above element of software web application page
are as bellow.
//input[@id='fk-top-search-box']
//input[contains(@name,'q')]
//input[starts-with(@class, "search-bar-text")]
//input[@id='fk-top-search-box' or @name='q']
//input[starts-with(@id, 'fk-top-search-box') and contains(@class,'fk-font-
13')]
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/09/drag-and-
drop.html");
}
@Test
public void dragAndDrop() {
//Locate element which you wants to drag.
WebElement dragElementFrom =
driver.findElement(By.xpath("//div[@id='dragdiv']"));
//Locate element where you wants to drop.
WebElement dropElementTo =
driver.findElement(By.xpath("//div[@id='dropdiv']"));
//Use Actions class and Its members of WebDriver API to perform drag and
drop operation.
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(dragElementFrom)
.moveToElement(dropElementTo)
.release(dropElementTo)
.build();
dragAndDrop.perform();
}
}
Above example will drag the small square element on big square element. This is
just example. You can use this example as a reference to perform drag and drop
operation in your web application. If you wants to by specific X-Y pixel offset
then you can view THIS POST.
You can find more tutorials links HERE to start learning selenium WebDriver
from basic.
In above example, we have written total 6 lines to drag and drop an element. If
you wants convert those 6 lines in only 1 line then you can do it as bellow. Replace
bellow given 1 line with 6 lines of above example. It will do same thing.
new Actions(driver).dragAndDrop(dragElementFrom,
dropElementTo).build().perform();
So this is the way to perform drag and drop an element using selenium
WebDriver.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/09/drag-and-
drop.html");
}
@Test
public void dragAndDrop() throws InterruptedException {
//Locate element which you wants to drag.
WebElement dragElementFrom =
driver.findElement(By.xpath("//div[@id='dragdiv']"));
//To drag and drop element by 100 pixel offset In horizontal direction X.
new Actions(driver).dragAndDropBy(dragElementFrom, 100, 0).build()
.perform();
//To generate alert after horizontal direction drag and drop. VIEW EXAMPLE
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Element Is drag and drop by 100 pixel
offset In horizontal direction.');");
Thread.sleep(5000);
driver.switchTo().alert().accept();
//To drag and drop element by 100 pixel offset In Vertical direction Y.
new Actions(driver).dragAndDropBy(dragElementFrom, 0, 100).build()
.perform();
//To drag and drop element by -100 pixel offset In horizontal and -100
pixel offset In Vertical direction.
new Actions(driver).dragAndDropBy(dragElementFrom, -100, -100).build()
.perform();
//To generate alert after horizontal and vertical direction drag and drop.
javascript.executeScript("alert('Element Is drag and drop by -100 pixel
offset In horizontal and -100 pixel offset In Vertical direction.');");
Thread.sleep(5000);
driver.switchTo().alert().accept();
}
}
You can run It In your eclipse and observe the X Y direction movement
of software web element. So this is another example of selenium webdriver's
advanced user Interactions using Actions class.
new
Actions(driver).clickAndHold(dragElementFrom).moveByOffset(100,100).release()
.perform();
46: Can we perform drag and drop operation In Selenium WebDriver? Tell
me a syntax to drag X element and drop It on Y element.
Answer: Yes, We can perform drag and drop operation using selenium
webdriver software testing tool's Advanced User Interactions API. Syntax is
like below.
new Actions(driver).dragAndDrop(X, Y).build().perform();
47: Do you have faced any technical challenges with Selenium WebDriver
software test automation?
Answer: Yes, I have faced below given technical challenges during selenium
webdriver test cases development and running for software web application.
Sometimes (Not always), Some elements like text box, buttons etc. are
taking more time(more than given Implicit wait time) to appear on page of
software web application or to get enabled on page. In such situation, If I have
used only Implicit wait then my test case can run fine on first run but It may fail
to find element on second run. So we need provide special treatment for such
elements so that webdriver script wait for element to be present or get enabled on
page of software web application during test execution. We can use Explicit wait
to handle this situation. You can find different explicit wait example links
on THIS PAGE.
Handling dynamic changing ID to locate element is tricky. If element's ID
Is changing every time when you reload the software web application page and
you have to use that ID In XPath to locate element then you have to use functions
like starts-with(@id,'post-body-') or contains(@id,'post-body-') In XPath. Other
alternate solutions to handle this situation are described in answer of Question 15
of THIS PAGE.
Clicking on sub menus which are getting rendered on mouse hover of main
menu is somewhat tricky. You need to use webdriver's Actions class to perform
mouse hover operation. You can VIEW FULL EXAMPLE on how to generate
mouse hover event on main menu.
If you have to execute your test cases in multiple browsers then one test
case can run successfully In Firefox browser but same test case may fail In IE
browser due to the timing related Issues (nosuchelement exception) because test
execution In Firefox browser Is faster than IE browser. You can resolve this Issue
by Increasing Implicit wait time when you run your test In IE browser.
Above Issue can arise due to the unsupported XPath In IE browser. In this
case, You need to you OTHER ELEMENT LOCATING METHODS (ID,
Name, CSSSelector etc.)to locate element.
Handling JQuery elements like moving pricing slider, date picker, drag and
drop etc.. Is tricky. You should have knowledge of webdriver's Advanced User
Interactions API to perform all these actions. You can find few example links for
working with JQuery Items on THIS PAGE.
Working with multiple Windows, Frames, and some tasks like Extracting
data from web table, Extracting data from dynamic web table, Extracting
all Links from page, Extracting all text box from page are also tricky and time
consuming during test case preparation.
There is not any direct command to upload or download files from web
page using selenium webdriver. For downloading files using selenium webdriver,
you need to create and set Firefox browser profile with webdriver test case. You
can VIEW PRACTICAL EXAMPLE.
Webdriver do not have any built In object repository facility. You can do
It using java .properties file to create object repository as described In THIS
EXAMPLE.
Webdriver do not have any built in framework or facility using which we
can achieve below given tasks directly: 1. Capturing screenshots, 2. generating
test execution log, 3. reading data from files, 4. Generating test result reports,
Manage test case execution sequence. To achieve all these tasks, we have to use
external services with webdriver like Log4J to generate log, Apache POI API to
read data from excel files, Testng XSLT reports to generate test result reports.
TestNG to manage test case execution, .properties file to create object repository.
All these tasks are very time consuming. ON THIS PAGE, I have described how
to create data driven framework step by step for selenium webdriver. That
framework contains all above functionality.
You can share other webdriver technical challenges which you have faced by
commenting below so that your experience can help to others too.
48: Can you tell me a syntax to close current webdriver Instance and to
close all opened webdriver Instances?
Answer:
Yes, To close current WebDriver Instance, We can use Close() method as
bellow.
driver.close();
If there are opened multiple webdriver Instances and wants to close all of them
then we can use webdriver's quit() method as bellow in software automation
test.
driver.quit();
Answer:
Yes, we can execute javascript during webdriver software test execution. To
generate alert, you can write bellow given code In your script.
Answer:
We can read alert message string as bellow.
driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
Answer:
1. Bitmap comparison is not possible using selenium webdriver software testing
tool.
2. Automating captcha is not possible. (Few peoples says we can
automate captcha but I am telling you If you can automate any captcha then It Is
not a captcha).
3. We can not read bar code using selenium webdriver software testing tool.
55: Write sample JUnit @Test method that passes when expected
ArithmeticException thrown.
Answer: For creating JUnit software test suite, we have to create test cases class
files and one separate test suite file. Then we can write syntax like bellow in test
suite file to run test suite.
@RunWith(Suite.class)
@SuiteClasses({junittest1.class, junittest2.class })
public class junittestsuite {
In above example, junittest1.class and junittest2.class are test case class names.
VIEW PRACTICAL EXAMPLE on how to create and run JUnit test suite with
selenium WebDriver.
61: For what purpose, assertTrue and assertFalse assertions are used?
Answer: In selenium webdriver software test automation, We need to assert
Boolean conditions true and false. We can assert both these conditions using
assertTrue and assertFalse JUnit assertions.
We can use TestNg with selenium webdriver software testing tool to configure
and run test cases very easily, easy to understand, read and manage test cases, and
to generate HTML or XSLT test reports.
You will find Selenium WebDriver with TestNG practical example Links
on PAGE 1 and PAGE 2.
65: Describe the similarities and difference between JUnit and TestNG unit
testing frameworks.
Answer: You can find all the similarities and difference between JUnit and
TestNG framework on THIS PAGE.
66: How to Install TestNG In Eclipse? How do you verify that TestNg Is
Installed properly In Eclipse?
We can define software testing test suite using set of test cases to run
them from single place.
Can Include or exclude test methods from software web application's test
execution.
Can specify a group to Include or exclude.
Can pass parameter to use in test case of software web application.
Can specify group dependencies.
Can configure parallel test execution for software web application.
Can define listeners.
69: How to pass parameter with testng.xml file to use It In test case?
Answer: We can define parameter In testng.xml file using syntax like bellow.
Here, name attribute defines parameter name and value defines value of that
parameter. Then we can use that parameter in selenium webdriver software
automation test case using bellow given syntax.
@Parameters ({"browser"})
VIEW FULL EXAMPLE on how to define and use parameter from testng.xml
file.
70: I have a test case with two @Test methods. I wants to exclude one
@Test method from execution. Can I do it? How?
Answer: Yes you need to specify @Test method exclusion In testng.xml file as
bellow.
You need to provide @Test method name in exclude tag to exclude it from
execution.
Answer: You can use bellow given syntax Inside @Test method to skip It from
test execution.
It will throw skip exception and @Test method will be sipped immediately from
execution. You can VIEW FULL EXAMPLE on how to skip @Test method
from execution.
<test>
<suite>
<class>
</methods>
</classes>
<suite>
<test>
</classes>
<class>
</methods>
Using priority, We can control @Test method execution manner as per our
requirement. That means @Test method with priority = 0 will be executed 1st and
@Test method with priority = 1 will be executed 2nd and so on. VIEW
PRACTICAL EXAMPLE to know how to use It.
Answer: There are many different assertions available In TestNG but generally I
am using bellow given assertions In my test cases.
1. assertEquals VIEW EXAMPLE
2. assertNotEquals VIEW EXAMPLE
3. assertTrue VIEW EXAMPLE
4. assertFalse VIEW EXAMPLE
5. assertNull VIEW EXAMPLE
6. assertNotNull VIEW EXAMPLE
75: Can you tell me usage of TestNG Soft Assertion In selenium webdriver
software testing tool?
Answer: Using TestNG soft assertion, we can continue our test execution even if
assertion fails. That means on failure of soft assertion, remaining part of @Test
method will be executed and assertion failure will be reported at the end of @Test
method. VIEW PRACTICAL EXAMPLE.
76: How to write regular expression In testng.xml file to search @Test
methods containing "product" keyword.
Answer: Time unit we provide on @Test method level or test suite level Is In
milliseconds. You can VIEW FULL EXAMPLE to know how to set time out.
78: What Is the syntax to get value from text box and store It In variable.
Answer: Most of the time, String In text box will be stored as value. So we need
to access value attribute(getAttribute) of that text box as shown In bellow
example.
String Result =
driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value"
);
VIEW PRACTICAL EXAMPLE to get text from calc result text box.
80: Tell me looks like XPath of sibling Input element which Is after Div in
the DOM.
81: Tell me looks like CSSSelector path of sibling Input element which Is
after Div in the DOM.
Answer: Dependency Is very good feature of testng using which we can set
software test method as dependent test method of any other single or multiple or
group of test methods. That means depends-on method will be executed first and
then dependent test method will be executed. If depends-on software test method
will fail then execution of dependent test method will be skipped automatically.
TestNG dependency feature will works only If depends-on test method Is part of
same class or part of Inherited base class. DETAILED DESCRIPTION ON
DEPENDENCY.
86: What Is the syntax to set test method dependency on multiple test
methods.
@Test(dependsOnMethods={"Login","checkMail"})
public void LogOut() {
System.out.println("LogOut Test code.");
}
Above test method Is depends on Login and checkMail test methods. VIEW
EXAMPLE.
Answer: We can use attribute enabled = false with @Test annotation to set test
method disabled. Syntax Is as bellow.
@Test(enabled = false)
public void LogOut() {
System.out.println("LogOut Test code.");
}
Answer : We can use bellow given two functions with XPath to find element for
software web page using attribute value from beginning.
1. contains()
2. starts-with()
89 : I have used findElements In my software test case. It Is
returning NoSuchElementException when not element found. Correct me If
I am wrong.
Answer : If Firefox browsers Is Installed at some different place than the usual
place then you needs to provide the actual path of Firefox.exe file as bellow.
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla
Firefox\\Firefox.exe");
driver =new FirefoxDriver();
Answer : You can view detailed answer for firefox custom profile on THIS
PAGE.
93 : Tell me the class name using which we can generate Action chain.
Answer : The WebDriver class name Using which we can generate Action chain
Is "Actions". VIEW USAGE OF ACTIONS CLASS with practical example on
how to generate series of actions to drag and drop element of software web
application.
94 : Do you know method name using which we can builds up the actions
chain?
Answer : Few of the examples are bellow where can use actions class to perform
operations In software web application.
Drag and drop element - VIEW EXAMPLE
Drag and drop by x,y pixel offset - VIEW EXAMPLE
Selecting JQuery selectable Items - VIEW EXAMPLE
Moving JQuery slider - VIEW EXAMPLE
Re-sizing JQuery re-sizable element - VIEW EXAMPLE
Selecting date from JQuery date picker - VIEW EXAMPLE
96 : Can we capture screenshot In Selenium WebDriver software testing
tool? How?
97 : Selenium WebDriver has any built In method using which we can read
data from excel file?
Answer : No, Selenium webdriver software testing tool do not have any built In
functionality using which we can read data from excel file.
98 : Do you know any external API name using which we can read data from
excel file?
Answer :
We can use jxl API (Java Excel API) to read data from excel file. VIEW
EXAMPLE
We can use one more powerful API known as Apache POI API to read and
write data In excel file. I have created data driven framework using Apache POI
API. You can VIEW DATADRIVEN FRAMEWORK CREATION
TUTORIALS step by step.
99 : Tell me any 5 webdriver common exceptions which you faced during
software test case execution.
100 : Tell me different ways to type text In text box In selenium software test.
Answer : We can type text In text box of software web application page using
bellow given ways In selenium test.
driver.findElement(By.xpath("//input[@id='fname']")).sendKeys("Using
sendKeys");
2. Using JavascriptExecutor
((JavascriptExecutor)driver).executeScript("document.getElementById('fname').
value='Using JavascriptExecutor'");
driver.findElement(By.xpath("//input[@id='fname']")).click();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_U);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_N);
robot.keyPress(KeyEvent.VK_G);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_R);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_B);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_T);
If above syntax return "false" means element Is not present on page and "true"
means element Is present on page.
If this returns "true" means element Is not present on page and "false" means
element Is present on page.
Answer : Webdriver launch fresh browser Instance when we run software tests
In Firefox browser using selenium webdriver. Fresh browser Instance do not have
any Installed add-ons, saved passwords, bookmarks and any other user
preferences. So we need to create custom profile of Firefox browser to get any of
this thing In Webdriver launched browser. VIEW MORE DETAIL WITH
EXAMPLE
Answer :
getAttribute() method Is useful to read software web app element's attribute
value like id, name, type etc. VIEW EXAMPLE.
getText() method Is useful to read text from element or alert. VIEW
EXAMPLE.
105 : What is the difference between WebDriver and Remote WebDriver?
Answer : Yes. If you are using TestNG with selenium webdriver software testing
tool then you can do Is using grouping approach as described In THIS PAGE.
Create separate group for those 20 test cases and configure testng.xml file
accordingly to run only those 20 test cases.
Also If you are using data driven framework then you can configure It In excel
file. You can configure such data driven framework at your own by following
steps given on THIS PAGE.
107 : Can you tell me three different ways to refresh page. Do not
use .refresh() method.
Answer : We can refresh browser In many different ways. Three of them are as
bellow.
driver.get(driver.getCurrentUrl());
driver.navigate().to(driver.getCurrentUrl());
driver.findElement(By.xpath("//h1[@class='title']")).sendKeys(Keys.F5);
108 : I wants to pass parameter In software test case through testng.xml file.
How can I do It?
Answer : You can use <parameter> node under <test> node In testng.xml file
with parameter name and value. Then you can use @Parameters annotation with
parameter name In your test case of software web application. VIEW USAGE
OF @PARAMETER ANNOTATION.
109 : My page contains file upload field but I am not able to upload file using
selenium webdriver software testing tool. Is there any other way using which
I can upload file In selenium test?
Answer : If you are not able to upload file using selenium webdriver then you
can create file upload script In AutoIT and then you can use It In selenium
webdriver software test. You can refer bellow given articles to learn more about
It.
What Is AutoIT V3
Steps To Download And Install AutoIT V3
Creating AutoIt Script To Upload File On Web Page
Upload File In Selenium WebDriver Using AutoIt
110 : I wants to set size and position of my browser window. Do you know
how to do it in selenium webdriver?
Answer : We can use setSize function to set size of window and setPosition
function to set position of browser window. VIEW EXAMPLE.
111 : Is there any way to get size and position of browser window in selenium
webdriver?
112 : I wants to scroll my software web application page by 300 pixel. Tell
me how can i do it?
1. Introduction Of TestNG
2. TestNG Installation Steps
3. Similarities and Difference Between TestNG and JUnit
4. Create And Run First TestNG-WebDriver Test
5. TestNg annotations with examples
6. Creating And Running WebDriver Test Suit Using testng.xml
File
7. Creating Single Or Multiple Tests For Multiple Classes
8. Creating Test Suite Using Class From Different Packages
9. Creating Test Suite Using Selected Or All Packages
10. Including Only Selected Test Methods In Selenium WebDriver-
TestNg Test
11. testng.xml - Include/Exclude Selenium WebDriver Test
Package
12. testng.xml - Using Regular Expression To Include/Exclude Test
Method
13. testng.xml - Skip Test Intentionally Using SkipException()
14. Data driven Testing using @DataProvider Annotation Of
TestNG
15. Parallel test execution In multiple browsers using @Parameters
annotation
Above given syntax will create new instance of Firefox driver. VIEW
PRACTICAL EXAMPLE
driver.get("http://only-testing-blog.blogspot.com/2013/11/new-test.html");
This syntax will open specified URL of software web application in web
browser. VIEW PRACTICAL EXAMPLE OF OPEN URL
driver.findElement(By.id("submitButton")).click();
This syntax will retrieve text from targeted element of software web application
page and will store it in variable = dropdown. VIEW PRACTICAL
EXAMPLE OF Get Text
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
This syntax will force webdriver to wait for 15 second if element not found on
page of software web application. VIEW PRACTICAL EXAMPLE OF
IMPLICIT WAIT
Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7
seconds" to be appear on targeted element. VIWE DIFFERENT
PRACTICAL EXAMPLES OF EXPLICIT WAIT
driver.getTitle();
It will retrieve page title and you can store it in variable to use in next
steps. VIEW PRACTICAL EXAMPLE OF GET TITLE
driver.getCurrentUrl();
It will retrieve current page URL and you can use it to compare with your
expected URL. VIEW PRACTICAL EXAMPLE OF GET CURRENT URL
10. Get domain name using java script executor
Above syntax will retrieve your software application's domain name using
webdriver's java script executor interface and store it in to
variable. VIEW GET DOMAIN NAME PRACTICAL EXAMPLE.
It will generate alert during your selenium webdriver test case execution. VIEW
PRACTICAL EXAMPLE OF GENERATE ALERT USING SELENIUM
WEBDRIVER.
It will select value from drop down list using visible text value = "Audi".
Select By Value
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
It will remove all selections from list box of software application's page.
isMultiple()
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
It will return true if select box is multiselect else it will return false.VIEW
PRACTICAL EXAMPLE OF isMultiple()
13. Navigate to URL or Back or Forward in Selenium Webdriver
driver.navigate().to("http://only-testing-
blog.blogspot.com/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step back and
3rd command will navigate one step forward.VIEW PRACTICAL
EXAMPLES OF NAVIGATION COMMANDS.
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
It will return true if element is present on page, else it will return false in
variable iselementpresent. VIEW PRACTICAL EXAMPLE OF VERIFY
ELEMENT PRESENT.
Above given steps with helps you to get window handle and then how to switch
from one window to another window. VIEW PRACTICAL EXAMPLE OF
HANDLING MULTIPLE WINDOWS IN WEBDRIVER
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not. You
can use it for any input element. VIEW PRACTICAL EXAMPLE OF
VERIFY ELEMENT IS ENABLED OR NOT.
assertEquals
Assert.assertEquals(actual, expected);
assertEquals assertion helps you to assert actual and expected equal
values. VIEW PRACTICAL EXAMPLE OF assertEquals ASSERTION
assertNotEquals
Assert.assertNotEquals(actual, expected);
assertNotEquals assertion is useful to assert not equal values. VIEW
PRACTICAL EXAMPLE OF assertNotEquals ASSERTION.
assertTrue
Assert.assertTrue(condition);
assertTrue assertion works for boolean value true assertion. VIEW
PRACTICAL EXAMPLE OF assertTrue ASSERTION.
assertFalse
Assert.assertFalse(condition);
assertFalse assertion works for boolean value false assertion. VIEW
PRACTICAL EXAMPLE OF assertFalse ASSERTION.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT
FORM.
driver.switchTo().alert().accept();
To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT
driver.switchTo().alert().dismiss();
To dismiss confirmation. VIEW PRACTICAL EXAMPLE OF CANCEL
CONFIRMATION
driver.switchTo().alert().sendKeys("This Is John");
To type text In text box of prompt popup. VIEW PRACTICAL EXAMPLE
OF TYPE TEXT IN PROMPT TEXT BOX
Create selenium webdriver data driven framework from scratch @This Page.
How to get the class name of element
You can get the class name of element using firebug add-on software as shown
in bellow given image.
Look in to above image. Post date content has a class and we can use that class
name to store that blog post date string. Notice one more thing in above image,
blog post date string has not any ID so we can not locate it by ID.
driver.findElement(By.className("date-header"));
import java.util.concurrent.TimeUnit;
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;
@Before
public void beforetest() {
@After
public void aftertest() {
driver.quit();
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
String datentime = driver.findElement(By.className("date-
header")).getText();//Locating element by className and store its text to
variable datentime.
System.out.print(datentime);
}
In above example,
Open Browser
WebDriver driver = new FirefoxDriver() will open webdriver's Firefox
browser instance.
Open URL
driver.get(); will open targeted URL in browser.
View THIS POST to know how to run webdriver test in google chrome and
View THIS POST to know how to run webdriver test in IE browser..
First of all I recommend you to read all these selenium IDE element locating
methodsand then read this article about Selenium WebDriver element locators to
get all locating methods in better way.
WebDriver software testing tool which is also known as a Selenium 2 has many
different ways of locating element. Let me explain each of them with examples.
Here I am explaining how to locate element By id and will describe Locating
Web Element By ClassName in my Next Post and others in latter posts.
Locating UI Element By ID
If your software web application's page element has unique and static ID then you
can locate your page element by ID. Look in to bellow given image. You can
verify that your webelement has any id or not using the firebug.
In above image, Submit Query button has unique id = 'submitButton'. I can use
that id to locate button as bellow.
driver.findElement(By.id("submitButton"));
Bellow given example will show you how to locate element by id and then how
to click on it. Copy bellow given @Test method part and replace it with the
@Test method part of example given on this page.(Note : @Test method is
marked with pink color in that example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
for (int i = 0; i<=20; i++)
{
WebElement btn = driver.findElement(By.id("submitButton"));//Locating
element by id
if (btn.isEnabled())
{
//if webelement's attribute found enabled then this code will be
executed.
System.out.print("\nCongr8s... Button is enabled and webdriver is
clicking on it now");
}
else
{
//if webelement's attribute found disabled then this code will be
executed.
System.out.print("\nSorry but Button is disabled right now..");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Selenium Webdriver software testing tool has one special method to submit any
formand that method name Is submit(). submit() method works same as clicking
on submit button.
WEBDRIVER TUTORIAL PART 2
Final Notes :
1. If any form has submit button which has type = "button" then .submit() method
will not work.
2. If button Is not Inside <form> tag then .submit() method will not work.
Now let us take a look at very simple example where I have used .submit() method
to submit form on software web page. In bellow given example, I have not used
.click() method but used .submit() method with company name field. Run bellow
given example In eclipse with testng and verify the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-
blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void LogIn_Test(){
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("MyFName"
);
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("MyLName")
;
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys("My
Email ID");
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys("My Mob
No.");
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys("My Comp
Name");
//To submit form.
//You can use any other Input field's(First Name, Last Name etc.) xpath
too In bellow given syntax.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}
Above example will simply submit the form and retrieve submission alert to print.
So this way we can use webdriver's submit method to submit any form. You can
try different form for your better understanding.
Now supposing, software web element do not have any ID or Class Name then
how to locate that element in selenium WebDriver ? Answer is there are many
alternatives of selenium WebDriver element locators and one of them
is Locating Element By Tag Name.
Locating Element By Tag Name is not too much popular because in most of cases,
we will have other alternatives of element locators. But yes if there is not any
alternative then you can use element's DOM Tag Name to locate that element in
webdriver.
(Note : You can view all tutorials of webdriver element locators)
Look in to above image. That select box drop down do not have any ID or Class
Name. Now if we wants to locate that element then we can use it's DOM tag name
'select' to locate that element. Element locator sysntex will be as bellow.
driver.findElement(By.tagName("select"));
Bellow given example will locate dropdown element by it's tagName to store its
values in variable. Copy bellow given @Test method part and replace it with the
@Test method part of example given on this page.(Note : @Test method is
marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by tagName and store its text in to variable dropdown.
String dropdown = driver.findElement(By.tagName("select")).getText();
System.out.print("Drop down list values are as bellow :\n"+dropdown);
}
Selenium Webdriver Element Locator -
Locating Element By Name With Example
Selenium WebDriver/Selenium 2 is web and mobile software application
regression testing tool and it is using element locators to find out and perform
actions on web elements of software application. We have learn Element
Locating by ID, Element Locating By Tag Name and Locating element by
Class Name with examples in my previous posts. Locating Element By Name is
very useful method and many
peoples are using this method in their webdriver software automation test case
preparation. Locating Element By Name and Locating Element by ID are nearly
same. In Locating Element by ID method, webdriver will look for the specified
ID attribute and inLocating Element By Name method, webdriver will look for
the specified Name attribute on page of software web application.
Let me show you one example of how to locate element by name on page of
software web application and then we will use it in our webdriver test case for
software web application.
Look in to above image, web element 'First Name' input box do not have any ID
so webdriver can not locate it By ID but that element contains name attribute. So
webdriver can locate it By Name attribute. Syntax of locating element in
webdriver is as bellow.
driver.findElement(By.name("fname"));
Now let we use it in one practical example as bellow.Copy bellow given @Test
method part and replace it with the @Test method part of example given on this
page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by Name and type given texts in to input box.
driver.findElement(By.name("fname")).sendKeys("My First Name");
}
Above example will type the text in text box using By Name element locating
method.
If you have a scenario where you need to wait for title then you can
use titleContains(java.lang.String title) with webdriver wait. You need to provide
some part of your expected software web application page title with this condition
as bellow.
In above syntax, ": MyTest" is my web page's expected title and 15 seconds is
max waiting time to appear title on web page. If title will not appears within 15
seconds due to the any reason then your test case will fails with timeout error.
First run bellow given test case in your eclipse and then try same test case for
your own software application.
Copy bellow given @Test method part of wait for title example and replace it
with the @Test method part of example given on this page. (Note : @Test
method is marked with pink color in that linked page).
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
driver.findElement(By.xpath("//a[contains(text(),'Click Here')]")).click();
Sometimes in your test case, you needs to store your software web
application page title to compare it with expected page title. In selenium IDE, we
can use "storeTitle" command to store it in variable. In webdriver ,we can do it
directly usingdriver.getTitle(); as shown in this example. But if you wants to do
it using javascript then how will you do it?
Copy bellow given @Test method part of get page title using javascript example
and replace it with the @Test method part of example given on this page. (Note
: @Test method is marked with pink color in that linked page).
@Test
public void test ()
{
JavascriptExecutor javascript = (JavascriptExecutor) driver;
Last 2 syntax will get current page URLs and Print it in console.
Look here, software application's domain name is different than the current page
URL.
Example : Get current URL of page and domain name in selenium webdriver
Copy bellow given @Test method part of get current software web
application's page URL using javascript example and replace it with the @Test
method part of example given on THIS PAGE. (Note : @Test method is
marked with pink color in that linked page).
@Test
public void test ()
{
String CurrentURL = driver.getCurrentUrl();
System.out.println("My Current URL Is : "+CurrentURL);
In above example, 1st 2 syntax will get and print current page URL. Last 3 syntax
will get domain name using javascript and will print it in console.
If you remember, we can generate alert in selenium IDE software testing tool too
using "runScript" command. THIS POST will describe you how to generate alert
in selenium IDE software testing tool using "runScript" command with example.
Now let me describe you how to generate alert in selenium webdriver software
automation if required during test case execution of your software web
application.
Copy bellow given @Test method part of generate alert using javascript
example and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
//Generating Alert Using Javascript Executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
Thread.sleep(2000);
driver.switchTo().alert().accept();
}
In above example, Java Script Executor will simply execute the javascript and
generate alert. You can your own alert text in it. Try it in your own software
application test if required.
Use Of isMultiple() And deselectAll() In
Selenium WebDriver With Example
Now you can easily select or deselect any specific option from select box or
drop down as described in my earlier POST 1, POST 2and POST 3. All these
three posts will describe you different alternative ways of selecting options from
list box or drop down. Now let me take you one step ahead to describe you the
use of deselectAll() and isMultiple() methods in selenium webdriver.
deselectAll() Method
deselectAll() method is useful to remove selection from all selected options of
select box. It will works with multiple select box when you need to remove all
selections. Syntax for deselectAll() method is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
isMultiple() Method
isMultiple() method is useful to verify if targeted select box is multiple select box
or not means we can select multiple options from that select box or not. It will
return boolean (true or false) value. We can use it with if condition before working
with select box. Syntax is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
System.out.print(value);
Bellow given example will show you use of isMultiple() and deselectAll()
methods very clearly in selenium webdriver.
@Test
public void test () throws InterruptedException
{
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
//To verify that specific select box supports multiple select or not.
if(listbox.isMultiple())
{
System.out.print("Multiple selections is supported");
listbox.selectByVisibleText("USA");
listbox.selectByValue("Russia");
listbox.selectByIndex(5);
Thread.sleep(3000);
In above example, if condition will check that listbox is multiple select box or
not? Used listbox.deselectAll(); to remove all selected options.
2. Deselect By Value
You can also deselect option from list box by value. 2nd syntax will deselect
option by value = Mexico.
3. Deselect By Index
Bellow given syntax will remove selection by index = 5.
Execute bellow given example in eclipse and observe results during execution.
Copy bellow given @Test method part of deselect option by visible text or
value or index and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that linked
page).
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
listbox.selectByValue("Japan");
listbox.selectByValue("Mexico");
Thread.sleep(1000);
listbox.selectByIndex(4);
listbox.selectByIndex(5);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(1000);
}
}
You can view MORE webdriver examples on THIS LINK.
First of all let me show you difference between visible text, value and index of
list box option. Bellow given image will show you clear difference between value,
visible text and index.
1. Select Option By Value In WebDriver
Syntax for selecting option by value in webdriver is as bellow. First syntax will
locate the select element from page of software web application and 2nd syntax
will select the option from select box by value = Italy.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
Copy bellow given @Test method part of select option by value or index and
replace it with the @Test method part of example given on THIS PAGE.(Note
: @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
driver.findElement(By.xpath("//input[@value='->']")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
Create selenium webdriver data driven framework from scratch @This Page.
If you know, In selenium IDE software testing tool we can select value from drop
down list using "select" or "addSelection" command. Now let me give you
example of how to select value from drop down list in webdriver.
Now we can use "Select" class to identify drop down from web page by writing
bellow given syntax.
Now we can select any value from selected drop down as bellow.
mydrpdwn.selectByVisibleText("Audi");
Full Example to select value from drop down of software applications's web
page is as bellow.
EXAMPLE
package junitreportpackage;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@After
public void aftertest() {
driver.quit();
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");
}
Same thing we can do for list box to select option from list box by visible text.
View my previous post to know how to select value by index from drop down.
1. driver.navigate().to
If you wants to navigate on specific software web application page or URL in
between your software test then you can use driver.navigate().to command as
bellow.
driver.navigate().to("http://only-testing-
blog.blogspot.com/2014/01/textbox.html");
2. driver.navigate().back();
This command is useful to go back on previous page. Same as we are clicking
browser back button. You can use this command as bellow. In Selenium IDE
software testing tool, we can use "goBack" to perform same action.
driver.navigate().back();
3. driver.navigate().forward();
Same as we are clicking on forward button of browser.
Bellow given example will cover all three commands. Execute it in your eclipse
to know them practically.
Copy bellow given @Test method part of driver.navigate() command examples
and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
driver.navigate().to("http://only-testing-
blog.blogspot.in/2014/01/textbox.html");
Yes we can do it very easily in WebDriver too using bellow given syntax.
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
We have to use findElements() method for this purpose. Above syntax will return
true if element is present on page of software web application. Else it will return
false. You can put if condition to take action based on presence of element on
page of software web application.
Bellow given example will check the presence of different text box on page. It
will print message in console based on presence of element.
Copy bellow given @Test method part of iselementpresent example and replace
it with the @Test method part of example given on THIS PAGE. (Note
: @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
for (int i=1; i<6; i++)
{
Then we have to store it in our local drive using bellow given syntax. You can
change/provide your own file destination path and name.
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
Now we need to import bellow given header files to get support of capture
screenshot in webdriver.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
Copy bellow given @Test method part of Capture screen shot webdriver
example and replace it with the @Test method part of example given on THIS
PAGE. Don't forget to import above given header files in your eclipse
test.(Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException, IOException
{
//Capture entire page screenshot and then store it to destination drive
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
System.out.print("Screenshot is captured and stored in your D: Drive");
}
You can put above syntax under catch block of try to capture screenshot on
failure. You can view THIS POST If you wants to record video for your
selenium webdriver software test execution.
Above example will only move mouse on targeted element of software web
application. It will not perform click operation. To perform click operation on
sub menu, we need to use click() action before perform() as shown in bellow
example.
package junitreportpackage;
import java.io.IOException;
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;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/p/mouse-hover.html");
}
@After
public void aftertest() {
driver.quit();
@Test
public void test () throws InterruptedException, IOException
{
actions.moveToElement(moveonmenu).moveToElement(driver.findElement(By.xpath("
//div[@id='menu1choices']/a"))).click().perform();
If you wants to work with multiple tabs then view THIS POST and wants to
work with multiple IFrames then view THIS POST.
WebDriver.getWindowHandles()
In WebDriver software testing tool, We can use
"WebDriver.getWindowHandles()" to get the handles of all opened windows by
webdriver and then we can use that window handle to switch from from one
window to another window. Example Syntax for getting window handles is as
bellow.
driver.switchTo().window(window2);
@Test
public void test () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page')]")).click();
isEnabled()
isEnabled() webdriver method will verify and return true if specified element is
enabled. Else it will return false. Generic syntax to store and print element's status
value is as bellow.
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
We can use isEnabled() method with if condition to take action based on element's
enabled status on page of software web application. Bellow given example will
explain you deeply about isEnabled() webdriver method. If you are using
selenium IDE software testing tool then VIEW THIS POST to know how to wait
for targeted element becomes editable.
Copy bellow given @Test method part of check element enabled status and
replace it with the @Test method part of example given on THIS PAGE. (Note
: @Test method is marked with pink color in that linked page).
@Test
public void test () throws BiffException, IOException, InterruptedException
{
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
WebElement firstname =
driver.findElement(By.xpath("//input[@name='fname']"));
WebElement lastname =
driver.findElement(By.xpath("//input[@name='lname']"));
//Verify First name text box is enabled or not and then print related
message.
if(firstname.isEnabled())
{
System.out.print("\nText box First name is enabled. Take your action.");
}
else
{
System.out.print("\nText box First name is disabled. Take your action.");
}
//Verify Last name text box is enabled or not and then print related
message.
if(lastname.isEnabled())
{
System.out.print("\nText box Last name is enabled. Take your action.");
}
else
{
System.out.print("\nText box Last name is disabled. Take your action.");
}
}
Above given example, will check the status of First name and Last name text box
and print message in console based on element is enabled or disabled.
Copy bellow given @Test method part of enable or disable element and replace
it with the @Test method part of example given on THIS PAGE. (Note
: @Test method is marked with pink color in that linked page).
@Test
public void test () throws BiffException, IOException, InterruptedException
{
boolean fbefore =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print("\nBefore : First Name Text box enabled status is :
"+fbefore);
boolean lbefore =
driver.findElement(By.xpath("//input[@name='lname']")).isEnabled();
System.out.print("\nBefore : Last Name Text box enabled status is :
"+lbefore);
Thread.sleep(2000);
boolean fafter =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print("\nAfter : First Name Text box enabled status is :
"+fafter);
boolean lafter =
driver.findElement(By.xpath("//input[@name='lname']")).isEnabled();
System.out.print("\nAfter : Last Name Text box enabled status is :
"+lafter);
Alert Popup
Generally alert message popup display on page of software web application with
alert text and Ok button as shown In bellow given Image.
Confirmation Popup
Confirmation popup displays on page of software web application with
confirmation text, Ok and Cancel button as shown In bellow given Image.
Prompt Popup
Prompts will have prompt text, Input text box, Ok and Cancel buttons.
Selenium webdriver software testing tool has Its own Alert Interface to handle all
above different popups. Alert Interface has different methods like accept(),
dismiss(), getText(), sendKeys(java.lang.String keysToSend) and we can use all
these methods to perform different actions on popups.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
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.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//Alert Pop up Handling.
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
//To locate alert.
Alert A1 = driver.switchTo().alert();
//To read the text from alert popup.
String Alert1 = A1.getText();
System.out.println(Alert1);
Thread.sleep(2000);
//To accept/Click Ok on alert popup.
A1.accept();
This way you can handle different kind of alerts very easily using Alert
Interface of selenium webdriver software automation testing tool. Next post will
show you how to handle unexpected alerts In selenium webdriver.
To handle this kind of unexpected alerts, You must at least aware about on which
action such unexpected alert Is generated. Sometimes, They are generated during
software web application page load and sometime they are generated when you
perform some action. So first of all we have to note down the action where such
unexpected alert Is generated and then we can check for alert after performing
that action. We need to use try catch block for checking such unexpected alters
because If we will use direct code(without try catch) to accept or dismiss alert
and If alert not appears then our test case will fail. try catch can handle both
situations.
I have one example where alert Is displaying when loading software web page.
So we can check for alert Inside try catch block after page load as shown In bellow
given example. After loading page, It will check for alert. If alert Is there on the
page then It will dismiss It else It will go to catch block and print message as
shown In bellow given example.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//To handle unexpected alert on page load.
try{
driver.switchTo().alert().dismiss();
}catch(Exception e){
System.out.println("unexpected alert not present");
}
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname");
driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname");
driver.findElement(By.xpath("//input[@type='submit']")).click();
}
}
Above given webdriver code Is just for example. It Is just explaining the way of
using try catch block to handle unexpected alert. You can use such try catch block
In that area where you are facing unexpected alerts very frequently.
Let me give you one more practical example for the same. Sometimes if you want
tohighlight element of software web application page then you can use javascript
executor. If you remember, we were using "highlight" command in selenium IDE
tohighlight any element of web page.
Copy bellow given @Test method part of generate alert using javascript
example and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
HighlightMyElement(driver.findElement(By.xpath("//input[@name='fname']")));
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
HighlightMyElement(driver.findElement(By.xpath("//button[@onclick='myFunction
()']")));
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitBut
ton")));
HighlightMyElement(driver.findElement(By.cssSelector("#submitButton")));
driver.findElement(By.cssSelector("#submitButton")).click();
If you wants to read above shown font property In selenium webdriver then you
can do It using .getCssValue() Method. You can provide property name (Example
: font-family, font-size, font-weight, etc.) with .getCssValue() method to read Its
value.
Bellow given example will read values of font-size, color, font-family and text-
align properties of "Example Login Page" text.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-
blog.blogspot.in/2014/05/login.html");
}
@Test
public void readFontProperty(){
//Locate text string element to read It's font properties.
WebElement text = driver.findElement(By.xpath("//h1[contains(.,'Example
Login Page')]"));
You can use .getCssValue() method to get any other property value of any
element.
If you write implicit wait statement in you webdriver software testing script then
it will be applied automatically to all elements of your test case. I am suggesting
you to use Implicit wait in your all test script of software web application with 10
to 15 seconds. In webdriver, Implicit wait statement is as bellow.
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
Above statement will tell webdriver to wait for 15 seconds if targeted element not
found/not appears on page. Le we look at simple example to understand implicit
wait better.
Copy bellow given @Test method part and replace it with the @Test method
part of example given on this page. (Note : @Test method is marked with pink
color in that example).
@Test
public void test ()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
driver.findElement(By.xpath("//input[@name='namexyz']"));
}
In Above webdriver test case with JUnit example, 1st Element
'xpath("//input[@name='fname']")' will be found on page but element
xpath("//input[@name='namexyz']") is not there on page. So in this case
webdriver will wait for 15 to locate that element on page because we have written
implicit wait statement in our code. At last webdriver test will fail because
xpath("//input[@name='namexyz']") is not on the page.
import java.util.concurrent.TimeUnit;
import java.io.FileInputStream;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
//Wait for element to be clickable
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitBut
ton")));
driver.findElement(By.cssSelector("#submitButton")).click();
}
public void HighlightMyElement(WebElement element) {
for (int i = 0; i < 10; i++)
{
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: orange; border: 4px solid orange;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: pink; border: 4px solid pink;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: yellow; border: 4px solid yellow;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "");
}
}
}
Run bellow given practical example.in eclipse and see how it works.
Copy bellow given @Test method part of wait for text example and replace it
with the @Test method part of example given on this page. (Note : @Test
method is marked with pink color in that linked page).
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("alpesh");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitBut
ton1")));
driver.findElement(By.cssSelector("#submitButton")).click();
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div
[@id='timeLeft']"), "Time left: 7 seconds"));
}
Sometimes you will face wait for alert scenario where you have to wait for
alert before performing any action on your software application web page. If you
know, we can use "waitForAlert" command in selenium IDE to handle alerts.
In WebDriver/Selenium 2, You can use WebDriver's built in canned condition
alertIsPresent() with wait command as bellow.
Look in to above syntax. 1st syntax described how much time it has to wait and
2nd syntax describes the waiting condition. Here we have used alertIsPresent()
condition so it will wait for the alert on page. Let me give you full practical
example to describe scenario perfectly.
Copy paste bellow given test case in your eclipse with JUnit and then run it. You
can View how to configure eclipse with JUnit if you have no idea.
package junitreportpackage;
import java.util.concurrent.TimeUnit;
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.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/new-
testing.html");
}
@After
public void aftertest() {
driver.quit();
@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());
String alrt = driver.switchTo().alert().getText();
System.out.print(alrt);
}
Above example will wait for the alert on page and as soon as alert appears on
page, it will store alert text in variable 'alrt' and then will print to it in console.
If you have a scenario to wait till element visible on software web page
then selenium webdriver/Selenium 2 has its own method
named visibilityOfElementLocated(By locator) to check the visibility of element
on software web page. We can use this method with explicit webdriver wait
condition to wait till element visible of present on page. However, we can wait
for element to be clickable using elementToBeClickable(By locator) method as
described in THIS ARTICLE.
Syntax to wait till element visible on page is as bellow. It will wait max 15
seconds for element. As soon as element visible on page, webdriver will go for
executing next statement.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@i
d='text3']")));
Here is practical example of wait for element visible. Execute it once and then
use it for your software web application test scenario.
Copy bellow given @Test method part of wait for visibility of element
located example and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that linked
page).
@Test
public void test () throws InterruptedException, IOException
{
//To wait for element visible
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@i
d='text3']")));
driver.findElement(By.xpath("//input[@id='text3']")).sendKeys("Text box is
visible now");
System.out.print("Text box text3 is now visible");
In above syntax, you can change webdriver wait time from 15 to 20, 30 or more
as per your requirement. Also you can use anyOTHER ELEMENT
LOCATING METHODS except By.xpath. Practical example of webdriver wait
till element becomes invisible is as bellow.
Copy bellow given @Test method part of wait till element invisible and replace
it with the @Test method part of example given on THIS PAGE.(Note : @Test
method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException, IOException
{
//Wait for element invisible
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//input[
@id='text4']")));
findElement() method
We need to use findElement method frequently in our webdriver software
test case because this is the only way to locate any element in webdriver software
testing tool.
findElement method is useful to locating targeted single element.
If targeted element is not found on the page then it will
throw NoSuchElementException.
findElements() method
We are using findElements method just occasionally.
findElements method will return list of all the matching elements from
current page as per given element locator mechanism.
If not found any element on current page as per given element locator
mechanism, it will return empty list.
Now let me provide you simple practical example of findElement method and
findElements method to show you clear difference. You can VIEW ALL
PRACTICAL EXAMPLES OF SELENIUM WEBDRIVER one by one.
Copy bellow given @Test method part of findElement and findElements method
examples and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
WebElement option =
driver.findElement(By.xpath("//option[@id='country5']"));
System.out.print(option.getAttribute("id")+" - "+option.getText());
List<WebElement> options= driver.findElements(By.xpath("//option"));
System.out.println(options.size());
for(int i=0;i<=options.size();i++)
{
String str = options.get(i).getAttribute("id")+" -
"+options.get(i).getText();
System.out.println(str);
In above example, findElement will locate only targeted element and then print
its id and text in console while findElements will locate all those elements of
current page which are under given xpath = //option. for loop is used to print all
those element's id and text in console.
Same way you can locate all input elements, link elements etc..
using findElements method.
When you click on zip folder link, it will show you zip mirror links to
download folder. Download and save zip folder by clicking on mirror link.
Now Extract that zip folder and look inside that extracted folder. You will
find log4j-1.2.17.jar file in it.
2. Import log4j-1.2.17.jar file in your eclipse project from
Right click on your project folder and go to Build Path -> Configure
Build path. It will open java build path window as shown in bellow image.
Click on Add External JARs button and select log4j-1.2.17.jar file. It will
add log4j-1.2.17.jar file in your build path.
Click on OK button to close java build path window.
3. Create Properties folder under your project folder and
add log4j.properties file in it.
Create folder with name = Properties under your project by right clicking
on your project folder.
Click Here to download log4j.properties file and save it in Properties
folder which is created under your project folder.
Now your properties folder under project folder will looks like bellow.
7. Replace bellow given syntax in your class file and Run your test case.
@Test
public void test () throws InterruptedException
{
Logger log;
driver.findElement(By.id("text1")).sendKeys("My First Name");
log = Logger.getLogger(Mytesting.class);
log.info("Type In Text field.");
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
log = Logger.getLogger(Mytesting.class);
log.info("Select value from drop down.");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
}
When your test case for software web application is executed, Go to folder
= C:\Logs. log.log file will be created over there. Open that file and look in to it.
Log written in your software test case will be inserted in your log file. In above
example, Syntax marked with Pink color are written for inserting log. Now you
can write log at any place in your test case of software web application as shown
in above example.
Let us try to create object repository for simple calculator application given
on THIS PAGE and then will try to create test case for that calc software
application using object repository..
Give file name objects.properties on next window and click on Finish button.
It will add object.properties file under your package. Now copy paste bellow
given lines in objects.properties file. So now this objects.properties file Is object
repository for your web application page calc.
objects.properties file
#Created unique key for Id of all web elements.
# Example 'one' Is key and '1' Is ID of web element button 1.
one=1
two=2
three=3
four=4
five=5
six=6
seven=7
eight=8
nine=9
zero=0
equalsto=equals
cler=AC
result=Resultbox
plus=plus
minus=minus
mul=multiply
In above file, Left side value Is key and right side value Is element locator(by Id)
of all web elements of web calculator. You can use other element locator methods
too like xpath, css ect.. VISIT THIS LINK to view different element locator
methods of webdriver.
Now let us create webdriver test case to perform some operations on calculation.
In bellow given example, All the element locators are coming from
objects.properties file using obj.getProperty(key). Here key Is reference of
element locator value in objects.properties file.
package ObjectRepo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@BeforeMethod
public void openbrowser() throws IOException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}
@AfterMethod
public void closebrowser() {
driver.quit();
}
@Test
public void Calc_Operations() throws IOException{
//Create Object of Properties Class.
Properties obj = new Properties();
//Create Object of FileInputStream Class. Pass file path.
FileInputStream objfile = new
FileInputStream(System.getProperty("user.dir")+"\\src\\ObjectRepo\\objects.pr
operties");
//Pass object reference objfile to load method of Properties object.
obj.load(objfile);
Now supposing I have many such test cases and some one has changed Id of any
button of calc application then what I have to do? I have to modify all test cases?
Answer Is No. I just need to modify objects.properties file because I have not use
element's Id directly In any test case but I have Used just Its key reference In all
test cases.
This way you can create object repository of all your software web elements In
one .properties file. You can VIEW MORE TUTORIALS about selenium
webdriver.
Copy bellow given @Test method part of extract all links from software web
page and replace it with the @Test method part of example given on THIS
PAGE.(Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
try {
List<WebElement> no = driver.findElements(By.tagName("a"));
int nooflinks = no.size();
System.out.println(nooflinks);
for (WebElement pagelink : no)
{
String linktext = pagelink.getText();
String link = pagelink.getAttribute("href");
System.out.println(linktext+" ->");
System.out.println(link);
}
}catch (Exception e){
System.out.println("error "+e);
}
THIS LINK will show you many other basic action command examples. Have
you READ POST on how to find broken link from page?
WebDriver's In built findelements method will help us to find all text boxes from
software web page. If you know, Each simple text box are Input fields and will
have always attribute type = text and If It Is password text box then It's type will
be password as shown In bellow given Image.
In short we have to find all those Input fields where type = "text" or "password".
In bellow given example, I have used findelements method to find and store all
those elements In txtfields array list and then used for loop to type some text In
all of them.
package Testng_Pack;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser() {
driver = new FirefoxDriver();
}
@Test
public void Text() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//find all input fields where type = text or password and store them In
array list txtfields.
List<WebElement> txtfields =
driver.findElements(By.xpath("//input[@type='text' or @type='password']"));
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
This way we can extract all text box from software web page If required In any
scenario.
Look at the firebug view of above HTML table. In any web table, Number of <tr>
tags Inside <tbody> tag describes the number of rows of table. So you need to
calculate that there are how many <tr> tags Inside <tbody> tag. To get row count
for above given example table, we can use webdriver statement like bellow.
Now we have row count and column count. One more thing you require to read
data from table Is generating Xpath for each cell of column. Look at bellow given
xpath syntax of 1st cell's 1st and 2nd rows.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[2]/td[1]
Highlighted string Is common for both cell's xpath. Only changing Is row number
Inside tr node. So here we can pass Row_count variable's value Inside tr node.
Same way, look at bellow given xpath syntax of 1st and 2nd cells of 1st row.
Highlighted string Is common for both cell's xpath. Only changing Is column
number Inside td node. So here we can pass Col_count variable's value Inside td
node.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[2]
All above thing Is applied In bellow given example. Simply run It In your eclipse
using testng and observe output In console.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void print_data(){
//Get number of rows In table.
int Row_count = driver.findElements(By.xpath("//*[@id='post-body-
6522850981930750493']/div[1]/table/tbody/tr")).size();
System.out.println("Number Of Rows = "+Row_count);
Number Of Rows = 3
Number Of Columns = 6
11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36
Here you can see, all the values of table are extracted and printed.
In this table, Row number 1, 2 and 4 has 3 cells, Row number 3 has 2 Cells and
Row 5 has 1 cell. In this case, You need to do some extra code to handle these
dynamic cells of different rows. To do It, You need to find out the number of cells
of that specific row before retrieving data from It.
You can view more webdriver software testing tutorials with testng and
java WEBDRIVER TUTORIAL @PART 1 and WEBDRIVER
TUTORIAL @PART 2.
Bellow given example will first locate the row and then It will calculate the cells
from that row and then based on number of cells, It will retrieve cell data
Information.
Run bellow given example In your eclipse with testng which Is designed for
above given dynamic web table.
package Testng_Pack;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Handle_Dynamic_Webtable() {
//Loop will execute till the last cell of that specific row.
for (int column=0; column<columns_count; column++){
//To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number "+row+" and column number
"+column+" Is "+celtext);
}
System.out.println("--------------------------------------------------");
}
}
}
Above example will works for dynamic changing web table too where number
of rows changing every time you load the page or search for something.
If you have noticed, When you will run your selenium webdriver software
automation test In Firefox browser then WebDriver will open blank Firefox
browser like No bookmarks, No saved passwords, No addons etc.. as shown In
bellow given Image.
If you wants access of all these things In your selenium webdriver software
automation test browser then you have to create new profile of Firefox and set all
required properties In newly created profile and then you can access that profile
In webdriver using FirefoxProfile class of webdriver.
First Of all, Let us see how to create new profile of Firefox and then we will see
how to use that profile In your test.
Now you can make you required settings on this new created profile browser like
add your required addons, bookmark your required page, network settings, proxy
settings, etc.. and all other required settings.
package Testng_Pack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser() {
//Create object of webdriver's inbuilt class ProfilesIni to access Its
method getProfile.
ProfilesIni firProfiles = new ProfilesIni();
//Get access of newly created profile WebDriver_Profile.
FirefoxProfile wbdrverprofile =
firProfiles.getProfile("WebDriver_Profile");
//Pass wbdrverprofile parameter to FirefoxDriver.
driver = new FirefoxDriver(wbdrverprofile);
}
@Test
public void OpenURL(){
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
When you will run above given example, It will open Firefox browser with newly
created profile settings.
Why needs To Set Firefox Profile In Selenium WebDriver
To perform some actions In your selenium webdriver software automation test,
You need special Firefox profile. Some example actions are as bellow where we
need to set Firefox profile. We will learn more about how to perform all those
actions In Selenium webdriver software automation testing tool In my upcoming
posts.
If you have any example where we need to set Firefox profile properties then you
can share It with world by commenting bellow.
It Is tricky way to download file using selenium webdriver software testing tool.
Manually when you click on link to download file, It will show you dialogue to
save file In your local drive as shown In bellow given Image.
Now selenium webdriver software automation testing tool do not have any feature
to handle this save file dialogue. But yes, Selenium webdriver has one more very
good feature by which you do not need to handle that dialogue and you can
download any file very easily. We can do It using webdriver's Inbuilt class
FirefoxProfile and Its different methods. Before looking at example of
downloading file, Let me describe you some thing about file's MIME types. Yes
you must know MIME type of file which you wants to download using selenium
webdriver software testing tool.
You need to provide MIME type of file In your selenium webdriver test so that
you must be aware about It. There are many online tools available to know MIME
type of any file. Just google with "MIME checker" to find this kind of tools.
In our example given bellow, I have used MIME types as shown bellow for
different file types In bellow given selenium webdriver test.
package Testng_Pack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser() {
//Create object of FirefoxProfile in built class to access Its properties.
FirefoxProfile fprofile = new FirefoxProfile();
//Set Location to store files after downloading.
fprofile.setPreference("browser.download.dir", "D:\\WebDriverdownloads");
fprofile.setPreference("browser.download.folderList", 2);
//Set Preference to not show file download confirmation dialogue using MIME
types Of different file extension types.
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet;"//MIME types Of MS Excel File.
+ "application/pdf;" //MIME types Of PDF File.
+ "application/vnd.openxmlformats-
officedocument.wordprocessingml.document;" //MIME types Of MS doc File.
+ "text/plain;" //MIME types Of text File.
+ "text/csv"); //MIME types Of CSV File.
fprofile.setPreference( "browser.download.manager.showWhenStarting", false
);
fprofile.setPreference( "pdfjs.disabled", true );
//Pass fprofile parameter In webdriver to use preferences to download file.
driver = new FirefoxDriver(fprofile);
}
@Test
public void OpenURL() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//Download Text File
driver.findElement(By.xpath("//a[contains(.,'Download Text
File')]")).click();
Thread.sleep(5000);//To wait till file gets downloaded.
//Download PDF File
driver.findElement(By.xpath("//a[contains(.,'Download PDF
File')]")).click();
Thread.sleep(5000);
//Download CSV File
driver.findElement(By.xpath("//a[contains(.,'Download CSV
File')]")).click();
Thread.sleep(5000);
//Download Excel File
driver.findElement(By.xpath("//a[contains(.,'Download Excel
File')]")).click();
Thread.sleep(5000);
//Download Doc File
driver.findElement(By.xpath("//a[contains(.,'Download Doc
File')]")).click();
Thread.sleep(5000);
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
When you run above example, It will download all 5(Text, pdf, CSV, docx and
xlsx) files one by one and store them In D:\WebDriverdownloads folder
automatically as shown In bellow given example.
InterruptedException Is used with method OpenURL to handle checked
exception of Thread.sleep(5000). View detailed tutorials of exception handling
In selenium WebDriver software test automation on THIS LINK.
This way you can download any file using selenium webdriver like zip file, exe
file, etc.. Just know your file's MIME type and download It as shown In above
example.
Here, Xpath pattern Is same for all ajax auto suggest drop list Items. Only
changing Is Value Inside <tr> tag. See bellow xpath of 1st two Items of drop list.
//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr[1]/td/div/table/tbody/tr[1]/td
[1]/span
//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr[2]/td/div/table/tbody/tr[1]/td
[1]/span
So we will use for loop(As described In my THIS POST) to feed that changing
values to xpath of drop list different Items. Other one thing we need to consider
Is we don't know how many Items It will show In ajax drop list. Some keywords
show you 4 Items and some other will show you more than 4 Items In drop list.
To handle this dynamic changing list, We will USE TRY CATCH BLOCK to
catch the NoSuchElementException exception if not found next Item In ajax drop
list.
In bellow given example, we have used testng @DataProvider annotation. If you
know, @DataProvider annotation Is useful for data driven software automation
testing. THIS LINKED POST will describe you the usage of @DataProvider
annotation with detailed example and explanation.
Run bellow given example In your eclipse with testng and see how It Is retrieving
values from ajax drop list and print them In console.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://www.google.com");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test(dataProvider="search-data")
public void Search_Test(String Search){
driver.findElement(By.xpath("//input[@id='gbqfq']")).clear();
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys(Search);
int i=1;
int j=i+1;
try{
//for loop will run till the NoSuchElementException exception.
for(i=1; i<j;i++)
{
//Value of variable i Is used for creating xpath of drop list's
different elements.
String suggestion =
driver.findElement(By.xpath("//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbo
dy/tr["+i+"]/td/div/table/tbody/tr/td[1]/span")).getText();
System.out.println(suggestion);
j++;
}
}catch(Exception e){//Catch block will catch and handle the exception.
System.out.println("***Please search for another word***");
System.out.println();
}
}
}
This way you can also select specific from that suggestion for your searching
purpose. It Is very simple In selenium webdriver software testing tool. You can
use other or more search values In above example. To do It simply modify
@DataProvider annotation method.
On completion of zip folder download, extract that zip folder. You will
find jxl.jar file inside it.
Step 2 : Add jxl.jar in your project folder as a external jar.
Right click on your project folder in eclipse and go to Build Path ->
Configure Build path -> Libraries tab -> Click on Add External JARs button and
select jxl.jar.
For detailed description with image on how to add any external jar in your project
folder, You can follow step 2 of THIS POST .
Last Name text box will be disabled initially so I have used javascript executor to
enable it. You can view practical example with description for the same on THIS
LINK.
Copy bellow given @Test method part of data driven testing example and
replace it with the @Test method part of example given on THIS PAGE. (Note
: @Test method is marked with pink color in that linked page).
@Test
public void test () throws BiffException, IOException, InterruptedException
{
//Open MyDataSheet.xls file from given location.
FileInputStream fileinput = new FileInputStream("D:\\MyDataSheet.xls");
//Access first data sheet. getSheet(0) describes first sheet.
Workbook wbk = Workbook.getWorkbook(fileinput);
Sheet sheet = wbk.getSheet(0);
//Read data from the first data sheet of xls file and store it in array.
String TestData[][] = new String[sheet.getRows()][sheet.getColumns()];
//Type data in first name and last name text box from array.
for(int i=0;i<sheet.getRows();i++)
{
for (int j=0;j<sheet.getColumns();j++)
{
TestData[i][j] = sheet.getCell(j,i).getContents();
if(j%2==0)
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys(TestData[i][j
]);
}
else
{
driver.findElement(By.xpath("//input[@name='lname']")).sendKeys(TestData[i][j
]);
}
}
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='lname']")).clear();
}
Thread.sleep(1000);
Steps To Setup and configure Selenium Webdriver With Eclipse and Java
Downloaded 'webDriver Java client driver' will be in zip format. Extract and
save it in your system at path D:\selenium-2.33.0. There will be 'libs' folder, 2
jar files and change log in unzipped folder as shown in bellow figure. We will
use all these files for configuring webdriver in eclipse.
That's all about configuration of WebDriver software with eclipse. Now you are
ready to write your test in eclipse and run it in WebDriver.
Selenium is not just a single tool or a utility, rather a package of several testing tools and
for the same reason it is referred to as a Suite. Each of these tools is designed to cater
different testing and test environment requirements.
1. Functional Testing
2. Regression Testing
Q #6) What are the limitations of Selenium?
Following are the limitations of Selenium:
Origin is a sequential combination of scheme, host and port of the URL. For example, for a
URL http:// http://www.softwaretestinghelp.com/resources/, the origin is a combination of
http, softwaretestinghelp.com, 80 correspondingly.
Thus the Selenium Core (JavaScript Program) cannot access the elements from an origin
that is different from where it was launched. For Example, if I have launched the JavaScript
Program from “http://www.softwaretestinghelp.com”, then I would be able to access the
pages within the same domain such as “http://www.softwaretestinghelp.com/resources” or
“http://www.softwaretestinghelp.com/istqb-free-updates/”. The other domains like
google.com, seleniumhq.org would no more be accessible.
So, In order to handle same origin policy, Selenium Remote Control was introduced.
Q #15) When should I use Selenium Grid?
Selenium Grid can be used to execute same or different test scripts on multiple platforms
and browsers concurrently so as to achieve distributed test execution, testing under
different environments and saving execution time remarkably.
Q #16) What do we mean by Selenium 1 and Selenium 2?
Selenium RC and WebDriver, in a combination are popularly known as Selenium 2. Selenium
RC alone is also referred as Selenium 1.
Q #17) Which is the latest Selenium tool?
WebDriver
FirefoxDriver
InternetExplorerDriver
ChromeDriver
SafariDriver
OperaDriver
AndroidDriver
IPhoneDriver
HtmlUnitDriver
Q #20) What are the different types of waits available in WebDriver?
There are two types of waits available in WebDriver:
1. Implicit Wait
2. Explicit Wait
Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds)
between each consecutive test step/command across the entire test script. Thus,
subsequent test step would only execute when the 30 seconds have elapsed after executing
the previous test step/command.
Explicit Wait: Explicit waits are used to halt the execution till the time a particular
condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit waits are
applied for a particular instance only.
Q #21) How to type in a textbox using Selenium?
User can use sendKeys(“String to be entered”) to enter the string in the textbox.
Syntax:
WebElement username = drv.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);
Q #22) How can you find if an element in displayed on the screen?
WebDriver facilitates the user with the following methods to check the visibility of the web
elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons,
labels etc.
1. isDisplayed()
2. isSelected()
3. isEnabled()
Syntax:
isDisplayed():
boolean buttonPresence =
driver.findElement(By.id(“gbqfba”)).isDisplayed();
isSelected():
boolean buttonSelected =
driver.findElement(By.id(“gbqfba”)).isDisplayed();
isEnabled():
boolean searchIconEnabled =
driver.findElement(By.id(“gbqfb”)).isEnabled();
Q #23) How can we get a text of a web element?
Get command is used to retrieve the inner text of the specified web element. The command
doesn’t require any parameter but returns a string value. It is also one of the extensively
used commands for verification of messages, labels, errors etc displayed on the web pages.
Syntax:
String Text = driver.findElement(By.id(“Text”)).getText();
Q #24) How to select value in a dropdown?
Value in the drop down can be selected using WebDriver’s Select class.
Syntax:
selectByValue:
Select selectByValue
= newSelect(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);
selectByVisibleText:
Select selectByVisibleText = new Select
(driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);
selectByIndex:
Select selectByIndex
= newSelect(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);
Q #25) What are the different types of navigation commands?
Following are the navigation commands:
navigate().back() – The above command requires no parameters and takes back the user
to the previous webpage in the web browser’s history.
Sample code:
driver.navigate().back();
navigate().forward() – This command lets the user to navigate to the next web page with
reference to the browser’s history.
Sample code:
driver.navigate().forward();
navigate().refresh() – This command lets the user to refresh the current web page there
by reloading all the web elements.
Sample code:
driver.navigate().refresh();
navigate().to() – This command lets the user to launch a new web browser window and
navigate to the specified URL.
Sample code:
driver.navigate().to(“https://google.com”);
Q #26) How to click on a hyper link using linkText?
driver.findElement(By.linkText(“Google”)).click();
The command finds the element using link text and then click on that element and thus the
user would be re-directed to the corresponding page.
The above mentioned link can also be accessed by using the following command.
------------
driver.findElement(By.partialLinkText(“Goo”)).click();
The above command find the element based on the substring of the link provided in the
parenthesis and thus partialLinkText() finds the web element with the specified substring
and then clicks on it.
Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
Locating iframe using index
frame(index)
driver.switchTo().frame(0);
frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();
Q #28) When do we use findElement() and findElements()?
findElement(): findElement() is used to find the first element in the current web page
matching to the specified locator value. Take a note that only first matching element would
be fetched.
Syntax:
WebElement element
=driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web page
matching to the specified locator value. Take a note that all the matching elements would
be fetched and stored in the list of WebElements.
Syntax:
List <WebElement> elementList
=driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
Q #29) How to find more than one web element in the list?
At times, we may come across elements of same type like multiple hyperlinks, images etc
arranged in an ordered or unordered list. Thus, it makes absolute sense to deal with such
elements by a single piece of code and this can be done using WebElement List.
Sample Code
1 // Storing the list
6{
8 serviceProviderLinks.get(i).click();
10 driver.navigate().back();
11 }
Thus, In the following scenario, we have used Action Interface to mouse hover on a drop
down which then opens a list of options.
Sample Code:
1 // Instantiating Action Interface
actions.moveToElement(driver.findElement(By.id("id of the
4
dropdown"))).perform();
7 subLinkOption.click();
Syntax:
driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”);
Q #37) How to capture screenshot in WebDriver?
1 import org.junit.After;
2 import org.junit.Before;
3 import org.junit.Test;
4 import java.io.File;
5 import java.io.IOException;
6 import org.apache.commons.io.FileUtils;
7 import org.openqa.selenium.OutputType;
8 import org.openqa.selenium.TakesScreenshot;
9 import org.openqa.selenium.WebDriver;
10 import org.openqa.selenium.firefox.FirefoxDriver;
11
13 WebDriver driver;
14 @Before
17 driver.get("https://google.com");
18 }
19 @After
21 driver.quit();
22 }
23
24 @Test
2 FileUtils.copyFile(scrFile, newFile("C:\\CaptureScreenshot\\google.jpg"));
9
3
}
0
31 }
@Test: Annotation lets the system know that the method annotated as @Test is a
test method. There can be multiple test methods in a single test script.
@Before: Method annotated as @Before lets the system know that this method shall
be executed every time before each of the test method.
@After: Method annotated as @After lets the system know that this method shall be
executed every time after each of the test method.
@BeforeClass: Method annotated as @BeforeClass lets the system know that this
method shall be executed once before any of the test method.
@AfterClass: Method annotated as @AfterClass lets the system know that this
method shall be executed once after any of the test method.
@Ignore: Method annotated as @Ignore lets the system know that this method
shall not be executed.
Q #40) What is TestNG and how is it better than Junit?
TestNG is an advance framework designed in a way to leverage the benefits by both the
developers and testers. With the commencement of the frameworks, JUnit gained an
enormous popularity across the Java applications, Java developers and Java testers with
remarkably increasing the code quality. Despite being easy to use and straightforward, JUnit
has its own limitations which give rise to the need of bringing TestNG into the picture.
TestNG is an open source framework which is distributed under the Apache software License
and is readily available for download.
TestNG with WebDriver provides an efficient and effective test result format that can in turn
be shared with the stake holders to have a glimpse on the product’s/application’s health
thereby eliminating the drawback of WebDriver’s incapability to generate test reports.
TestNG has an inbuilt exception handling mechanism which lets the program to run without
terminating unexpectedly.
There are various advantages that make TestNG superior to JUnit. Some of them are:
2 import org.testng.annotations.*;
4 @Test(priority=0)
6 }
7 @Test(priority=1)
8 public void method2() {
9 }
10 @Test(priority=2)
12 }
13 }
4 JXL API doesn’t support rich text POI API supports rich
formatting text formatting
5 JXL API is faster than POI API POI API is slower than
JXL API
In Selenium, objects can be stored in an excel sheet which can be populated inside the
script whenever required.