Selenium WebDriver Installation Guide
Selenium WebDriver Installation Guide
com
Selenium: Webdriver:
It is a free and open source web application automation tool, which performs the action on the
application by calling native methods of the browser.
1) Required software’s:
2) JDK(Java development kit) latest version 1.7 or 1.8
3) Eclipse IDE
4) Mozilla Firefox browser
5) Selenium jar file
Ex:
package [Link];
import [Link];
publicclass demo {
Advantages:
1) Free :selenium can be used for commercial purpose also without purchasing the
licensee
2) Open source: you can view and download and customize the source code of
selenium itself.
3) Web application: any application which is opened browser and automated using
selenium
4) Ex: [Link], [Link]
Vinay2ml@[Link]
Interface
SearchContext
Web driver
Interface
RemoteWebDriver Class
FirefoxDriver ChromeDriver
4) How do you open the webpage without using the get method ()?
Webdriver driver = new FirefoxDriver ();
[Link] (‚[Link]
driver. Close ()
publicclass pythonfile {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("http:\\[Link]");
[Link]().to("http:\\[Link]");
[Link]().back();
[Link]().forward();
[Link]();
Vinay2ml@[Link]
}
7) How do you click on forward button in browser web page.
publicclass forwardback {
}else
{
[Link]("[Link] not laoded ");
}
[Link]();
}
}
8) How do you refresh the web page?
publicclass refreshpage {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver() ;
[Link]("[Link]
[Link]().refresh();
[Link]();
publicclass maxmizepage {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]().refresh(); //refresh the page
[Link]().window().maximize() ;
[Link]();
}
Vinay2ml@[Link]
10) Write a script open Google in web page and verify that google page is
loaded ?
publicclass gettitilepage {
publicclass gettitilepageignorecase {
11) Write a code to get the url present in the address bar ?
}
Vinay2ml@[Link]
Assignment:
1) Write a script open [Link] verify that is navigated to
[Link]
publicclass geturl {
Ex:
<html>
<title>Qspider</title>
<body>
Welcome !
</body>
</html>
Vinay2ml@[Link]
Create a table:
<html>
<body>
<table border =‛1‛>
<tbody>
<tr>
<th>snio</th>
<th>subject</th>
<th>Apply</th>
</tr>
<tr>
<td>1</td>
<td>Java</td>
<td>input type =‛checkbox‛></td>
</tr>
</tbody>
</table>
</body>
</html>
<Html tags>
<html>
<body>
<title>
Vinay2ml@[Link]
Any word which is present after the greater than symbol till
the end of respective html tag is called as text of the
element.
1)tagName - tag
2) id , name, className are called attribute
3) linkText, parstialLinkText, are called Text
4) CssSelector , xpath are called Expression
Ex:
<html>
Vinay2ml@[Link]
<body>
< a href =‛[Link] id =‛a1‛ name =‛n1‛ class
=‛c1‛>Qspider</a>
</body>
</html>
publicclass tagNameclick {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]([Link]("a")).click();
[Link]();
}
}
publicclass attribute_id {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]([Link]("a1")).click();
[Link]();
}
}
}
5) Selenium Script: To click on the link on the sample web page
using text property ‚linkText()‛ as locator.
publicclass testfindelement {
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
Vinay2ml@[Link]
[Link]([Link]("Qspider")).click();
}
6) Selenium Script: To click on the link on the sample web page
using text ‚PatrialLinkText() property as locator.
publicclass partiallinktext {
If specified locator is not matching with any of the element then findElement()
method will throw Exception ‚NoSuchElementException‛
Error ex:
Exception in thread "main" [Link]: Unable to
locate element: {"method":"partial link text","selector":"spider12"}
If the specified locator is matching with more than one element(duplicate) then
findElement() method returns first matching web Element.
Ex:
<html>
<body>
UN: <input type =‛text‛ ><br>
PW: <input type =‛Password‛>
</body>
</html>
In the above webpage to identify password filed, we cannot use the linkText() or
partialLinkText() as those not supported for the password filed. We can’t use the
id() , name() , className(), as it not given by the developer , we can’t use
tagName() as it is duplicate. In such scenario we can use the
cssSelector,(css(Cascaded style sheet)) with following syntax.
Htmltag[property =‛value‛]
publicclass cssselectorexpression {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link] ;
[Link]([Link]("input[type='text']")).sendKeys("vinay");
[Link]([Link]("input[type='password']")).sendKeys("Jugga")
;
[Link]();
}
}
Ex: input[id=’username’]
Input[class=’textField’]
Input[name=’username’]
Input[placeholder=’username’]
Ex: <html>
<body>
FN:<input type=‛text‛><br>
LN:<input type =‛text‛>
</body>
</html>
In the above webpage both first name and last name as same cssexpression, hence we
can’t enter the lastname in such cases we use Xpath.
Body
|
Input
|
A
|
Vinay2ml@[Link]
----Div1 input1
Input2
A
----Div2 input 1
->input 2
In order to view the source code of the element it is called as inspecting the
element use Firebug, which is Add-on for firebox browser. In order to install it in
the firefox browser.
Tools->Add-on
Tree structure:
Html
↓----body
|--div
|---input A
|--input B
|
|____div
|--input c
|-input D
Absolute xpath: specify the complete path of the element is called as absolute xpath.
Note: Navigating from parent node to the child node is called as forward traversing
Relative xpath: The absolute path is very lengthy instead of this we can use
releative xpath whith help of ‚//‛
1) Write the program to logout from the application without using any of
synchronization option?
publicclass withoutsync {
[Link]();
}
publicclass withoutclick {
publicclass changetext {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
WebElement un =[Link]([Link]("username"));
[Link]();
[Link]("vinay");
WebElement up =[Link]([Link]("password"));
Vinay2ml@[Link]
[Link]();
[Link]("Jugga");
[Link]();
}
4) Write a script change the text present in the text box without using the
clear() method ?
publicclass withoutclear
{
publicstaticvoid main(String[] args)
{
WebDriver driver =new FirefoxDriver();
[Link]("[Link]
WebElement un =[Link]([Link]("username"));
[Link]([Link],"a");
[Link]("manager");
[Link]();
}
5) Write a script to copy and paste text one box into another text box
publicclass copypaste {
WebElement up =[Link]([Link]("username"));
[Link]([Link],"a");
[Link]([Link],"c");
WebElement un =[Link]([Link]("password"));
[Link]();
[Link]([Link],"v");
[Link]();
}
1) Write a script to get text present in the text box.
Note: The text will be present inside an attribute called value, hence we
should use getAttribute() method.
publicclass gettext {
Vinay2ml@[Link]
String pass
=[Link]([Link]("password")).getAttribute("value");
[Link](pass);
[Link]();
}
Note: Can we return the pass word is present in the password filed using selenium?
Yes.
2) Write the script to get url of the link ?
publicclass geturl {
3) Write a script to get tool tip text of the link from the [Link]
publicclass tooltiptext {
[Link]("[Link]
r=hp_nmenu_sub_electronics_0_iPad");
String str1 =[Link]([Link]("Apple 16GB iPad Mini
with Wi-Fi")).getAttribute("title");
[Link](str1);
[Link]();
4) Write a script to get the price of IPad min present in the [Link]
Vinay2ml@[Link]
publicclass checkboxseleted {
}
else{
[Link]("check box is not selected");
}
[Link]();
}
5) How do you verify whether the button is enabled or not isEnabled() method
which returns Boolean value.
Ex:
Vinay2ml@[Link]
publicclass buttonenabled {
6) Write a script to verify weather username text box is displayed or not in the
login page.
Find Elements(findElements()):
In order to get multiple elements from the webpage we use findElements method which
returns List<WebElement> , Generally we use xpath for this method.
Ex:
1) Count all the links present on the webpage and clicking on the first link .
publicclass countlinks {
publicstaticvoid main(String[] args) {
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
List<WebElement> alllinks ;
alllinks =[Link]([Link]("//a")) ;
int linkcount= [Link]();
[Link](linkcount);
WebElement link = [Link](2);
[Link]() ;
[Link]();
2) Write a script to print text of the links which is present on the [Link]
except empty string
publicclass googlelinks {
[Link](countlinks);
int j =0;
for(int i =0 ;i < countlinks ;i++){
WebElement link = [Link](i);
String linktext = [Link]();
int linksize =[Link]();
// [Link](linktext);
if(linksize >0){
j+=1 ;
[Link](linktext);
}
[Link](j);
[Link]();
publicclass checkboxselect {
4) Write a script to select all the alternative checkbox present on the webpage
[Link]
publicclass alternativechboxselect {
[Link]();
}
5) Write a script to select all the checkbox present in the webpage in reverse
order.
publicclass reveresechkselect {
[Link]();
}
6) Write a script to select first and last checkbox present on the webpage?
publicclass firstlastchbox {
[Link](0).click();
[Link]([Link]()-1).click() ;
publicclass countimages {
[Link]().timeouts().implicitlyWait(10,[Link]) ;
[Link]("[Link] ;
List<WebElement> coutimgs = [Link]([Link]("//img")) ;
for(int i =0; i <[Link](); i++) {
String imges = [Link](i).getAttribute("title");
[Link](imges);
}
[Link]();
}
Handling the listbox: in webelement interface we do not have any appropriate method,
to handle the list box, in order to perform required action on list box we use Select
Class
Frist find the list boxElement ausing findElement() method, then pass it an
argument for Select class constructor and call any one of the select By method of the
select class as shown in the below.
publicclass Selectlistbox {
}
We can use same selectBymethod to handle Multi select list box .
1) Write a script to count the number of option present in the list box.
publicclass countlist {
[Link]();
2) Write a script to print all the option present in the list box ([Link])
publicclass listoptionprint {
}
[Link]() ;
3) Write a script to print all the selected options with multi selected list box
in reverse order.
publicclass multiselectedreverese {
[Link]();
4) Write a script to print name and text of the first selected option present in
the multiselected list box
if([Link]()){
[Link]("yes multiple list box");
}
else{
[Link]("not a mulit select list box ");
}
}
3) Write a script verify whether the given list box is mulityselect list box
dropdown combo box.
publicclass multyorcombo {
[Link]();
4) Write a script to select all the option present in the mulitselect list box.
publicclass Selectedoptiosn {
if([Link]()){
[Link]("yes multiple list box");
}
else{
[Link]("not a mulit select list box ");
}
[Link]();
}
But there is no select All method in order to Select all the option we should
write a looping code as shown in the above example.
5) Write a script to search for the Specified option present in the List box.
publicclass specifiedoption {
[Link]();
}
1) What is dynamic list box how to handle it , list box whoes content is keep
changing during runtime is called as dynamic list box, in order to handle
them use Select class itself. Along with Explicit wait.
Note: Most of the class dynamic element or developed using AJAX (Asynchrons
java script and XML) technology to handle Ajax element we use Explicit
wait().
Ex: Selecting the required in country list box which in state then
selecting respective state, in the state list box it is dynamic .
publicclass dyanmiclistbox {
[Link]([Link]().get(i).getAttribute("value"));
}
//[Link]("//option[@value='Gujarat']") ;
[Link]();
Handling customized List box any list box which is developed without using
Select HTML tag is called as customized list box.
Vinay2ml@[Link]
We can’t handle the customized list box, using Select class we try to use
it, we get unexpected tag name Exception.
publicclass custimzedlistbox {
2) Write a script to search selenium in google and print all the autosuggested
options.
publicclass searchprintautolist {
String xp = "//div[@class='sbqs_c']" ;
List<WebElement> autolist = [Link]([Link](xp));
for(int i =0 ; i< [Link](); i++){
//[Link]([Link](i).getAttribute("class"));
[Link]([Link](i).getText()) ;
}
[Link]();
}
publicclass chkautolist {
Note: if we try to perform any action on the element after the Element is reloaded or
disappeared or page refresh then we get StaleElementRefrence Exception
Drop down Menu: it is an element on which of we move the mouse pointer it will
display list of option (submenu).
Ex:
Vinay2ml@[Link]
//[Link]([Link]("//a[text()='Basic Facts']")).click();
[Link]([Link]("//a[text() ='Areas of
Expertise']")).click() ;
[Link]();
Context Menu: The list of option displayed when you right click on the page is called
as context menu:
In order to select the required option present in the context menu. Type the short
cut keys ‚such as ‚T‛ for new Tab, ‚w‛ for new Window, etc.. using sendkeys() methods
of Actions class as shown below.
publicclass contextmenu {
[Link]();
Performing Drag and drop in order to another location we use drag and drop method of
the action class.
[Link](source, target);
publicclass dragdrop {
[Link]();
Handling Pop-up:
Vinay2ml@[Link]
In selenium performing action on the pop-up depended on the type of the pop-up.
Some of the pop-up cannot be handled by selenium in such cases we use alternative
rd
option and 3 party tools.
publicclass captureimage {
Note:
Characteristics:
1) We can move the pop-up
2) We cannot inspect the pop-up
3) It will have ok button
4) If the ok and cancel button this is confirmation pop-up.
In order to handle the pop-up first we should transfer control to the Alert pop-up
using switch start it returns the object of type alert and we can use following
method of Alert class.
1) GetText() used to get the text of the pop-up.
2) Accept – used to click on ‚ok’ button
3) Dismiss- > used to click on cancel button
Note:
1) If Alert pop-up is not present it will throw NoAlretPresentException:
2) After closing the alert pop-up control will be transferred back to the
mainpage automatically.
3) There cannot be multiple alert pop-up at the same time, that is if multiple
pop –up displayed at the same time it will be other than the Alert pop-up.
4) Most of the cases will be hidden division pop-up or child browser pop-up.
5) If multiple alert pop-up displayed, then each time we should use switch to
statement.
Ex:
publicclass alertconfimation {
//[Link]([Link]("button")).click();
//[Link]([Link]("button")).click() ;
//[Link]([Link]("input[id ='button']")).click() ;
[Link]([Link]("//input[@id ='button']")).click() ;
try{
Vinay2ml@[Link]
}
catch(NoAlertPresentException e ){
[Link]("Alret is not present");
}
[Link]();
}
Since we are allowed to inspect the element we can handle this pop-up using
findElement() method itself.
Note: This is called hidden division pop-up because it is created using Html tag div
and initially its hidden (Display none)
2) Calendar pop-up is type of hidden division pop-up
Ex:
publicclass hiddendivisionpopup {
try {
[Link]([Link]("login")).sendKeys("vinay2ml@[Link]") ;
[Link]([Link]("password")).sendKeys("nokianokia123") ;
[Link]([Link]("password2")).sendKeys("nokianokia123") ;
Vinay2ml@[Link]
[Link]([Link]("//button[@onclick='return
doSignUp();']")).click();
//id="loginErrorMsg" class="body" align="left" style="color:red"
colspan="2"
String msg =
[Link]([Link]("loginErrorMsg")).getAttribute("id");
if([Link]("loginErrorMsg")){
[Link]([Link]("I already have account")).click()
;
}
[Link]([Link]("login")).sendKeys("vinay2ml@[Link]");
[Link]([Link]("password")).sendKeys("nokianokia123") ;
[Link]([Link]("//button[@onclick='return
doLogIn();']")).click() ;
catch(NoSuchElementException e){
[Link]("popup is not displayed");
}
}
publicclass calenderhandle {
[Link]([Link]("//input[@id='BE_flight_depart_date']")).click();
[Link]([Link]("//a[@id='a_2014_10_15']")).click() ;
2) How do you enter into the Textbox without using SendKeys() using java script.
Using JavaScript we can enter the text in the text box even if the textbox is
disabled.
Vinay2ml@[Link]
3) Write a script to select future date in the calendar without writing the
navigation code.
Note: this is pop-up is displayed while loading the webpage, hence it is called
as page onload pop-up.
Solution: Selenium can ‘not perform any action on page on-load pop-up in order to
handle it the specify user name and password in the url itself as shown in below.
Handling Database:
While testing the application some time we need to verify the data present in
the database also. In order to do this we should have the following information
of the database such as :
1) Data base type
2) Data base location
3) Username and password
4) Login to data base
5) Table structure (Data schema) and SQL knowledge
The connection string can be stored in a system variable called DSN (Data
source name)
We can create our own DSN connect to any required data base before creating the DSN
assume that required database driver installed in the system .
Note: in order to specify the username and password click on Advanced button.
publicclass connetingdatabase {
2) Write a code to count the no of column present in the table and also print
name of the column
publicclass countcolumnname {
publicstaticvoid main(String[] args) throws SQLException {
Connection c = [Link]("jdbc:odbc:actitime");
String sql = "select * from customer" ;
ResultSet r = [Link]().executeQuery(sql);
int cc = [Link]().getColumnCount() ;
[Link](cc);
[Link]() ;
}
Vinay2ml@[Link]
publicclass specifiedtable {
[Link]();
Note:
1) The above program can be used on any database on any system only DSN name
changes.
2) In JDBC column index start from 1 like xpath.
3) ResultSet do not have the hasnext() method ,next() method itself perform the
action of the hasnext() method
4) To retrieve data present in the cell of the table we alwasys use getString()
method irrespective of the cell data type. Later we may use wrapper class or
type casting to convert the data into required type.
TestNG is a unit testing tool. Basically used by developer to perform white box
testing that is every requirement given by the customer , developer develops a java
class which will be called as business class. If there are multiple requirements a
there will be multiple business class.
In order to test all the business class ( white box testing ) developer
develops corresponding test class in order to run all the test class together(Batch
execution ) developer uses TestNG. Which will also generate execution result
automatically in html format it also as other built in functions , such as :
Assertion , Re-execution of the failure scripts etc..
In selenium for every manual test cases we develop automation script in java
class. In order to execute all the selenium scripts to generate execution results
etc. we also use TestNg.
Vinay2ml@[Link]
Installing TestNG :
1) Open Eclipse go to help
2) Help Eclipse Marketplace Search Test NG
Note: if Eclipse marketplace is not available then select ‚install New software‛
under the help menu . clickAdd specify the name as TestNG location as :
[Link] Get the location url from [Link] web site.
3)
Test NG class:
2) Any method which is written below Test Annotation is called as Test Method.
3) @Test is called as Test Annotation syntactic metadata
Whenever we run any TestNG class it automatically generate the result in Html format
([Link]) or index html. Inside (Test-output) folder of the java
project
package [Link];
import [Link];
import [Link];
import [Link];
publicclass demo {
@Test
publicvoid testA()
{
[Link]("Login");
Vinay2ml@[Link]
package [Link];
import [Link];
import [Link];
publicclass priorityexp {
@Test(priority = 2)
publicvoid Deletecustomer()
{
[Link]("Delete the custoer") ;
@Test( priority = 3)
publicvoid Editcustomer()
{
[Link]("Edit the custoer ");
}
@Test(priority = 1)
publicvoid Registercustomer()
{
[Link]("Create the customer ");
}
}
Note:
1) giving the priority is not mandatory, if it is not provided its priority will
be zero (0)
2) it can give the negative number also for priority
3) Then priority is need not be in sequential order
4) The priority should always a number , it always execute in ascending order.
Ex:
package [Link];
import [Link];
import [Link];
import [Link];
publicclass dependsonmethodex {
@Test(dependsOnMethods ="Registercustor")
publicvoid deletecustoer()
{
[Link]("Delete custer depend on register") ;
}
@Test
publicvoid Registercustor()
{
[Link]("Register custoremr ") ;
[Link](false) ;
}
}
Note: in the above ex: frist it wil try to execute delete customer (because of
alphabetical order), but because of dependency it will execute first
registercustomer method. Which will fail during the runtime , hence it will
skip execution of delete customer method.
output:
[TestNG] Running:
C:\Users\viml\AppData\Local\Temp\testng-eclipse-142572682\[Link]
FAILED: Registercustor
SKIPPED: deletecustoer
===============================================
Default test
Tests run: 2, Failures: 1, Skips: 1
2) When the TestNG class is skip -> if the dependsonMethod is failed it will
skip the test method.
Using Assert class validation refers to comparing actual value with expected
value and reporting the status.
Ex:
package [Link];
import [Link];
import [Link];
import [Link];
publicclass assertequalscheck {
@Test
publicvoid Registercustormer(){
[Link]("Login") ;
[Link]("Register custmer") ;
String msg = "Created customer" ;
String emsg ="Created not customer" ;
[Link](msg, emsg);
[Link]("Logout");
}
}
Note: when we use Assertion it will compare the actual value with expected
value of both are same then the status will be pass, and it will continue the
execution of the reaming statement.
If actual and expected values are different the status will be failed
and it will stop the current test method execution. (But it will continue
execution reaming methods).
1) How do you ensure that Test will continue execution ever after the
verification failed.?
Using SoftAssert().
Ex:
publicclass usingsoftassert {
@Test
publicvoid registercustormer()
{
SoftAssert softassert = new SoftAssert() ;
[Link]("Login") ;
[Link]("register");
String msg ="created customer" ;
String emsg ="created" ;
[Link](msg, emsg);
Vinay2ml@[Link]
[Link]("logout") ;
[Link]();
Note: while verifying the important or critical features use assert that is the steps
where can not procced, because of the failure like blocker defect or showstopper. But
otherwise we can use softassert() method.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass DemoA {
@BeforeClass
publicvoid openApp()
{
[Link]("open the logs ",true);
}
@AfterClass
publicvoid closeApp()
{
[Link]("close the app",true);
}
Vinay2ml@[Link]
@BeforeMethod
publicvoid login()
{
[Link]("Login ",true);
}
@AfterMethod
publicvoid logout()
{
[Link]("logout",true);
}
@Test
publicvoid createcustomer()
{
[Link]("Registercusotmer",true);
}
@Test
publicvoid Deletecustomer()
{
[Link]("Delete coustomer",true);
}
}
Note: Other Annotation of TestNG ([Link]
1) @BeforeSuite
2) @AfterSuite
3) @BeforeTest
4) @AfterTest
5) @BeforeGroups
6) @AfterGroups
7) @Factory
8) @Listener
9) @parameters
10)@Dataprovider
Inheritance in TestNG
While developing Automation scriot for every manual testcase we write TestNG class
that is if we are autmomating 100 manual testcase we create 100 testNG class.
In every TestNG class ther may be common steps, such as Login and logout
.instead of writing those methods again and again we can use inheritance concept.
That is we develeop all the common methods in the parent class then inherted. In all
the TestNG class as show in the below example.
SupertestNG. Java
Login() Logout()
Vinay2ml@[Link]
[Link] [Link]
Createdcustomer() Deletedcustomer
---------------------------------------[Link]------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
publicclass SupertestNG
{
@BeforeMethod
publicvoid login()
{
[Link]("Login ", true) ;
@AfterMethod
publicvoid logout()
{
[Link]("Logout", true) ;
}
}
[Link]
package [Link];
import [Link];
import [Link];
------------------------[Link]-----------------------------
package [Link];
Vinay2ml@[Link]
import [Link];
import [Link];
}
}
Output:
Login
Create customer
Logout
Login
Delete customer
Logout
===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
Test suite:
It is an xml file which contains list of all the TestNG class which are to be
executed .
<suitename="Suite"parallel="none">
<testname="Test">
<classes>
<classname="[Link]"/>
<classname="[Link]"/>
</classes>
</test>
</suite>
In order to execute the TestNG suite Right click on the [Link] go to Run as
Select TestNG suite.
1) Script execution is successful But still we want to fail the script explicitly
?
[Link]()
import [Link];
import [Link];
import [Link];
publicvoid deletecustormer()
{
[Link]("Delete customer", true) ;
[Link]() ;
}
}
2) How do you re-execute only the failed script, when ever ther is failure in the
execution TestNG automatically creates [Link] file inside the test-
out floder which contains list of all the failed testNG class or method. So in
order to execute only the failed script Right click on the xml file go to run
as select TestNG suite.
Ex:
package [Link];
import [Link];
import [Link];
@Test(invocationCount =5)
publicvoid createcustomer()
{
[Link]("Create customer", true) ;
}
Output:
Login
Create customer
Logout
Login
Create customer
Logout
Login
Create customer
Logout
Login
Create customer
Logout
Vinay2ml@[Link]
Login
Create customer
Logout
PASSED: createcustomer
PASSED: createcustomer
PASSED: createcustomer
PASSED: createcustomer
PASSED: createcustomer
===============================================
Default test
Tests run: 5, Failures: 0, Skips: 0
ex:
package [Link];
import [Link];
import [Link];
import [Link];
publicclass dataproviderex {
@DataProvider(name ="logindata")
public Object[][] getData()
{
Object[][] data = new Object[2][2] ;
data[0][0] ="admin" ;
data[0][1] = 1234 ;
data[1][0] ="userA" ;
data[1][1] =3455;
return data ;
@Test(dataProvider="logindata")
publicvoid loginlogout(String un, int pin)
{
[Link]("enter un "+un, true) ;
[Link]("Enter pin" +pin, true) ;
[Link]("Click login ",true) ;
[Link]("click logout", true) ;
}
}
Output:
enter un admin
Enter pin1234
Click login
click logout
Vinay2ml@[Link]
enter un userA
Enter pin3455
Click login
click logout
PASSED: loginlogout("admin", 1234)
PASSED: loginlogout("userA", 3455)
===============================================
Default test
Tests run: 2, Failures: 0, Skips: 0
===============================================
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass DemoD {
@Parameters({"browser"})
@Test
publicvoid testD(String browser)
{
WebDriver driver ;
if([Link]("GC"))
{
[Link]("[Link]",
"C:/selenium/Selenium-Dump/[Link]") ;
Vinay2ml@[Link]
}
else
{
driver = new FirefoxDriver() ;
[Link]().timeouts().implicitlyWait(20,[Link]) ;
[Link]("[Link] ;
for(int i =1 ;i <=100 ; i++)
{
[Link]([Link]("username")).sendKeys("vinayjugga") ;
[Link]([Link]("username")).clear();
}
[Link]() ;
}
Note: we can’t execute above class directly because testMethod is taking the
parameter we should always run this from the TestNG suite.
[Link]
<suitename="Suite"parallel="tests">
<testname="GCTest">
<parametername="browser"value="GC"/>
<classes>
<classname="[Link]"/>
</classes>
</test><!-- Test -->
<testname="FFTest">
<parametername="browser"value="FF"/>
<classes>
<classname="[Link]"/>
</classes>
</test><!-- Test -->
</suite><!-- Suite -->
Ex:
package [Link];
Vinay2ml@[Link]
import [Link];
import [Link];
import [Link];
publicclass encapsulationex {
private WebElement un ;
private WebDriver driver ;
publicdemo()
{
un = [Link]([Link]("usename")) ;
}
1) Framework Design
2) Framework Implementation
3) Framework Execution
The above stages depends on type of the framework which is used in the automation.
We can broadly categorized the framework types as specified below irrespective of the
automation tools.
Note: with respect to selenium there are popular frameworks which are implemented
using any one of the above types.
Framework Design: Senior automation engineer or leads with their past experience will
design the automation framework.
1) They list of out of all the software files which are required for the
automation and then specify the folder structure and their purpose.
2) Required software:
1) JDK
2) Ecliepse +TestNG plugin
3) Firefox +Firebug +Firepath plugin
4) AutoIt
5) Google chrome browser
6) MS office
Note: ensure that all the mentioned software are installed and there are updated .
Required files:
1) .jar
2) .exe
3) .xls
4) .xml
5) .html
6) .bat
7) .class
8) .java
Note: Except first 3 types of files all the other files will have predefined location
such as :
In the java project folder we should create 3 floders to store the first 3 types of
files.
C:\AWS\Automation
1) Copy the selenium jar files into jarfile floder and [Link] and
[Link] copy paste into the exefiles.
Note: if we write any AuotIT script the framework implementation then autoIt script
also stored into the exefiles.
Simllarly if we any xlfiles for the test data it will be copy paste into the
excelfiles folder.
In eclipse IDE right click on the java project and Refresh which will display newly
created floder.
Vinay2ml@[Link]
Select all the jar files in the Java build path select library stack and click Add
external Jar files
This is the actual stage where we develop the required Methods and convert the Manual
test case’s into automation Script.
Before writing any code developer will consult architecture for the design of the
application in java 250 + Design solution are ready available which are called as
java design pattern .
Some of the famous and frequent used java design pattern are
1) Signleton
2) Multiton
3) Factory
4) Page object Module
For developing the web application page object model is best suitable.
This is the one of the java design pattern where the below rules to develop the
webpage.
Vinay2ml@[Link]
1) For every webpage present in the application developer develops 1 Java class.
2) Every java class should contain data members and constructor and member
function
3) Data member represent the elements present on the webpage and all the data
member should be private.
4) Constructor is used to initialize the element present on the webpage this
process is called as page decoration. In page object module we use parameter
side constructor.
5) All the method should be public and they are used to perform action on the
element in automation also we use page object module concept to test the
webpage.
Ex:
import [Link];
import [Link];
import [Link];
publicclass loginpage
{
private WebElement untexbox ;
Abstraction: hiding the implementation from the end user generally called as
abstraction .
We use this concept to reduce the burden on the end user and also reduce the
maintaince.
Ex: Instead of developing setter and getter method for every field we develop the
method based on the functionality
Ex: instead of developing 3 method to handle username and password and login button
sparetly , we develop method as shown below .
Vinay2ml@[Link]
publicclass loginpage
{
private WebElement untexbox ;
private WebElement loginbutton;
The end user just call a method to perform the login operation on the application
without knowing the actual implementation of the code.
Ex:
import [Link];
import [Link];
import [Link];
publicclass loginusage {
Page Factory:
Generally when we try to initialize the element in the constructor at the beginning
only so we may get exception, because the element may not be present at that time.
Ex:
Error msg is displayed only entering after the criditianls popup is displayed only
click in on after click login button get exception.
Vinay2ml@[Link]
While handling the very large webpage where it has too many elements will drastically
increase total length of the constructor.
Loading all the elements into the memory at a time will affect performance of the
script also to overcome the above issue we use Page factory.
In page factory we should declare the element using @FindBy Annoation and we use
initElements() methods to initialize all these elements during runtime instead of the
initial time this process is called as late binding or lassie initialization
Ex:
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass LoginPage
{
@FindBy(id ="username")
private WebElement untexbox ;
@FindBy(name ="pwd")
private WebElement passwd;
@FindBy(id ="loginButton")
private WebElement loginbutton ;
@FindBy(className ="errormsg")
private WebElement emsg;
{
return [Link]("value");
}
*/
mport [Link];
import [Link];
import [Link];
publicclass loginusage {
@FindBy(xpath =‛//a‛)
@FindBy we can’t use variable in FindBy Annotation. While specifying the value of the
locator .
Vinay2ml@[Link]
1) Testcase_ID :ActiveTime_LoginLogout()
Steps:
Enter valid username
Enter valid password
Enter on login button
Click on logout link
2) TestCase_ID: ActiveTime_CreateBilling()
Steps:
Enter valid user name and password
Click on login button
Click on setting and then click on Billing types
click on Create Billing Types
Enter the name ex: Automation and click on create Billing Type
Verify that following success Message displayed
Msg =‛Billing type has been successfully created‛
Click on logout
3) TestCase ID: ActiveTime_DeleteBilling()
Steps:
Login to activetime with valid username and password
Click on settings and click on billing types
Click on delete link on Autoatmion click ok on confirmation pop-up
Verify that following msg is displayed
Msg=‛Billing type has been successfully deleted.
Click on logout link
Note:
1) Execute the testcase manually at least once , its given more clarity on the
testcase should be automated
2) For the given testcase note down the elements and action perform on those
Elements based on the webpages
3) Some of the elements will be present in multiple webpages such as headers and
footers.
Page1: LoginPage
Elements: usernametextbox, pwtextbox, loginbutton
Methods:
Method1-------login()
Enter un
Enter pw
Click login
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass LoginPage
{
@FindBy(id ="username")
private WebElement untexbox ;
@FindBy(name ="pwd")
private WebElement passwd;
@FindBy(id ="loginButton")
private WebElement loginbutton ;
@FindBy(className ="errormsg")
private WebElement emsg;
Page2: BasePage
Methods:
Method1:----gotobillingpage()
Click on settings
Click on billing types
Method2: Logout()
import [Link];
import [Link];
import [Link];
import [Link];
publicclass BasePage {
@FindBy(id ="logoutLink")
private WebElement logoutLink;
publicvoid gotoBillingPage()
{
[Link]();
[Link]();
}
publicvoid logOut()
{
[Link]();
}
}
Vinay2ml@[Link]
Page3 : createnewBillingpage
Method1: CreateBilling()
Enter name
import [Link];
import [Link];
import [Link];
import [Link];
@FindBy(id="name")
private WebElement name;
Page4: BillingTypepages
Methods:
Methods1: clickcreateBillingTypes
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@FindBy(xpath ="//span[@class='successmsg']")
private WebElement amsg ;
@FindBy(xpath ="//a[text()='automation']/../../td[6]/a")
private WebElement deleteLink ;
publicvoid clickCreateBillingTypes()
{
[Link]();
}
}
Testcase_ID :ActiveTime_LoginLogout()
Steps:
Enter valid username
Enter valid password
Enter on login button
Click on logout link
import [Link];
@Test
publicvoidtestActiveTime_LoginLogout()
{
LoginPage loginpage = new LoginPage(driver) ;
[Link]("admin", "manager");
TestCase_ID: ActiveTime_CreateBilling()
Steps:
Enter valid user name and password
Click on login button
Click on setting and then click on Billing types
click on Create Billing Types
Enter the name ex: Automation and click on create Billing Type
Verify that following success Message displayed
Msg =‛Billing type has been successfully created‛
Click on logout
import [Link];
@Test
publicvoidtestActiveTime_createBilling(){
Vinay2ml@[Link]
[Link]() ;
[Link]();
[Link]() ;
}
}
Testing the application with multiple inputs is called as Data driver testing in
order to do this we take the test data from the Excel sheet.
In order to handle the excel sheet we use POI (Poor obfuscation implementation) jar
file provided by Apache which can be downloaded from the following website.
[Link]
Vinay2ml@[Link]
Download the zip file and copy paste the downloaded file into required location and
unzip.
Copy only below mentioned 5 jar file into the Jar file folder into the automation
framework.
Vinay2ml@[Link]
Associate all the above selected jar files into the java project.
Ex:
import [Link];
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass ExcelDemo {
Optimized code:
import [Link];
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass ExcelDemo1 {
Note:
1) Instead of the specify complete path of the XL file absolute path we can
specify Relative path using which represents the complete path of current JAVA
project.
2) FileInputStream will throw IOException (Checked exception)
Ex:
Exception in thread "main" [Link]:
.\excelfiles\[Link] (The system cannot find the file specified)
Ex:String v = [Link](100).getCell(0).getStringCellValue();
Exception in thread "main" [Link]
import [Link];
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass RowCount {
Note: getLastRowNum() return index of the last Row that is if the 10 rows are
present , it will return 9.
2) Write a script to count the number of cells present in the first Row.
import [Link];
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass CountCellfristRow {
Note: getLastCellNum() return the number of cell present in the specified Row and not
the Index.
3) Write a code to print number of cells present in the each row of the excel
sheet.
import [Link];
[Link];
import [Link];
import [Link];
Vinay2ml@[Link]
import [Link];
import [Link];
import [Link];
publicclass CountEachRowCell {
import [Link];
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass PrintContentXL {
}
[Link](" ");
}
Note: if any row and cell is blank in between then we get NullpointerException , we
should handle it using try catch block.
In order to store the value in the xl sheet we use SetCellValue() to Save the
XL file use write() method of workbook, which takes FileoutputStream as
argument as show in below
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
publicclass WritetoExcel {
[Link](10).createCell(0).setCellValue("Jugga");
}
Vinay2ml@[Link]
Generic Methods:
Any Method Which can be used in different projects or called as Generic methods.
Such as handling XL files and handling Database etc.
Any Method which can be used only with in the current project or called as Project
specific method.
Ex: All the methods develop under page object module, ex: createBilling,
DeleteBilling etc.
package [Link];
import [Link];
import [Link];
import [Link];
publicclass Excellib {
}
catch(Exception e)
{
Vinay2ml@[Link]
return"";
}
}
}
The 'Select' class in Selenium WebDriver is used to select and deselect options from drop-down lists that are implemented using the HTML <select> tag. It provides methods like 'selectByVisibleText()' to interact with standard list boxes. However, it cannot be used on customized list boxes that don't use the <select> tag, as this results in an 'unexpected tag name Exception'. Instead, customized list boxes are handled using methods like 'sendKeys()' .
In TestNG, a test suite is set up using annotations such as '@BeforeMethod' to perform login before each test, and '@AfterMethod' to perform logout after each test. '@BeforeClass' and '@AfterClass' can initialize and clean up resources before and after all test methods respectively. Tests are annotated with '@Test'. A suite can be executed via an XML file that lists all relevant TestNG classes and defines execution order .
The 'findElements()' method returns a List of WebElements and does not throw an exception if no elements are found, whereas 'findElement()' returns a single WebElement and throws a 'NoSuchElementException' if no elements match. 'findElements()' can return an empty list, while 'findElement()' throws an exception if no elements match .
Dynamic list boxes have content that changes during runtime, often implemented using AJAX. Unlike static list boxes, their options are not predetermined. To handle dynamic list boxes, Selenium's 'Select' class is used in conjunction with explicit waits to ensure elements are loaded before interacting with them, which is critical due to the asynchronous changes in the list content .
TestNG uses a file called 'testng-failed.xml', which is automatically created in the 'test-output' folder after a test run. This file lists all failed test cases, allowing users to easily re-execute only the failed tests by running this XML file as a TestNG suite .
TestNG facilitates parallel test execution by using the 'parallel' attribute in the TestNG XML configuration file. The attribute can be set to 'tests' or 'methods' to enable concurrent execution. Additionally, '@Parameters' are used in test methods to specify conditions like browser choice for execution. This setup reduces the overall test run time by executing multiple tests simultaneously .
Data-driven testing in Selenium using TestNG and Apache POI involves executing test cases using multiple data inputs stored in an Excel sheet. Apache POI is used to read and write data to/from Excel files. This approach allows for extensive test coverage by running the same test with various data sets, enhancing test robustness and reusability. Its advantages include flexibility in handling large data sets and ease of managing test data externally .
The 'isSelected()' method can be used to confirm if a checkbox is selected in Selenium WebDriver. It returns a boolean value. In a script, it is implemented by finding the checkbox element using 'findElement()', then calling 'isSelected()' on that element. For example: If 'chebox1.isSelected()' is true, it prints 'Check box is selected', otherwise 'check box is not selected' .
The 'WorkbookFactory' class in Apache POI is crucial for creating a 'Workbook' instance from a file input stream, regardless of the Excel file format (XLS or XLSX). In a Selenium test script, it's used to read data from Excel by parsing the file into a 'Workbook', accessing sheets, rows, and cells to retrieve test data, enabling data-driven testing .
In Selenium, to select all options in a multi-select list box, a developer uses a loop to iterate over each option and select it individually. There is no direct 'select all' method because the 'Select' class operates on individual selections, reflecting standard HTML form control limitations, hence requiring a scripted iterative approach .