You can parametrize your test cases using excel sheet. With the help you TestNG we can pass different set of data to our test cases by following steps
1. create a data file excel rename column as username and fill below data like
username
test1
test2
test3
test4
2. create a dsn through control pannel--> administrative tool--> Data source (ODBC) --> select system dsn --> click add
then select "dirver do microsoft excel" select workbook your data file which you created above.
now your data source and provider is ready now connect this in your test cases using java class for
Class.forName("sun.jdbc.odbc.
JdbcOdbcDriver");
3. Write the test cases
import org.openqa.selenium.server.RemoteControlConfiguration;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;
public class TestExcel extends SeleneseTestBase {
@BeforeClass
public void setUp()throws Exception{
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.trustAllSSLCertificates();
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost",4444,"*iexplore","http://www.yahoo.com");
seleniumServer.start();
selenium.start();
}
@Test
public void testread()throws Exception{
// Connection connection = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection( "jdbc:odbc:nk" );
// Connection con = DriverManager.getConnection( "jdbc:odbc:nk" ); here you write your driver which you created using ODBC connecting excel workbook.
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( "Select * from [Sheet1$]" );
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue);
selenium.open("/");
pause(5000);
selenium.click("link=Sign in");
selenium.waitForPageToLoad("30000");
try {
if (selenium.isElementPresent("//a[@id='overridelink']"))
selenium.click("//a[@id='overridelink']");
}
catch (Exception e) {}
pause(30000);
selenium.type("userid", columnValue);
selenium.type("pass","password");
selenium.click("//button[@class='bfbt' and @type='submit']");
pause(8000);
String wc = selenium.getTable("//div[@id='dynamicmenu-hdrCtr']/table[1].0.1");
System.out.print(wc);
selenium.click("link=Sign out");
selenium.waitForPageToLoad("20000");
selenium.isTextPresent("Welcome!");
}
System.out.println("");
}
st.close();
con.close();
} catch(Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());
}
}
}
Monday, November 29, 2010
How to setup Selenium RC with TestNG in eclipse
TestNG Annotation
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@Parameters: Describes how to pass parameters to a @Test method.
Test case
goolgesearch.java
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;
import com.thoughtworks.selenium.*;
public class googlesearch extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
@BeforeClass
@Parameters({"selenium.host","selenium.port","selenium.browser","selenium.url"})
public void setUp(String host, String port, String browser , String url ) throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium(host, Integer.parseInt(port), browser, url);
seleniumServer.start();
selenium.start();
}
@Test
@Parameters({"search","expected"})
public void googling(String search, String expected) {
selenium.open("/");
selenium.waitForPageToLoad("6000");
selenium.type("q", search);
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent(expected));
}
@AfterTest
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumServer.stop();
}
}
# Install TestNG plug-in in your eclipse.
# Set the java build path and pointing to RC sever.
Go to Java project and right click on it then select properties then select java build path then select library tab and select external jar pointing you selenium RC server.
# Run the test case as TestNG test suite.
Go to googlesearch.java page right click on the page the click on Run as... and select the suite in the dialog box which you created above.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@Parameters: Describes how to pass parameters to a @Test method.
Test case
goolgesearch.java
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;
import com.thoughtworks.selenium.*;
public class googlesearch extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
@BeforeClass
@Parameters({"selenium.host","selenium.port","selenium.browser","selenium.url"})
public void setUp(String host, String port, String browser , String url ) throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium(host, Integer.parseInt(port), browser, url);
seleniumServer.start();
selenium.start();
}
@Test
@Parameters({"search","expected"})
public void googling(String search, String expected) {
selenium.open("/");
selenium.waitForPageToLoad("6000");
selenium.type("q", search);
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent(expected));
}
@AfterTest
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumServer.stop();
}
}
# Install TestNG plug-in in your eclipse.
# Set the java build path and pointing to RC sever.
Go to Java project and right click on it then select properties then select java build path then select library tab and select external jar pointing you selenium RC server.
# Run the test case as TestNG test suite.
Go to googlesearch.java page right click on the page the click on Run as... and select the suite in the dialog box which you created above.
How to upload a file in selenium
How to upload a file in selenium with the help of AutoIT
Recently, I had the challenge of writing some automation for a workflow which included uploading a file because uloading a file works on windows component.
selenium is unable to access windows components and it will be handled through AutoIT.
Once you are able to click on browse button and a dialog box is open to choose the file then you just run a AutoIT script which will help to select the file from your local or remote drive and control will come to your web page to proceed with selenium.
Step to choose a file from your local or remote drive
Step 1.
Download the AutoIT and intall it.
Download AutoIT from its homepage
step 2.
write a AutoIT script to choose a file from your local or remote drive.
#include
; Internet Explorer is partly integrated in shell.application
$oShell = ObjCreate("shell.application") ; Get the Windows Shell Object
$oShellWindows=$oShell.windows ; Get the collection of open shell Windows
$MyIExplorer=""
for $Window in $oShellWindows ; Count all existing shell windows
; Note: Internet Explorer appends a slash to the URL in it's window name
if StringInStr($Window.LocationURL,"http://") then
$MyIExplorer=$Window
exitloop
endif
next
$oForm = _IEGetObjByName ($MyIExplorer, "UploadedFile")
_IEAction($oForm, "click")
WinActivate("Choose file");
Local $file = "C:\Documents and Settings\intelizen\Desktop\selenium.txt"
ControlSetText("Choose file", "", "Edit1", $file )
ControlClick("Choose file", "", "Button2")
setp 3.
Complie AutoIT script and make exe of that script.
Right click on that saved script file and click on "Compile script" from context menu. This will make an exe file of that script.
setp 4.
Call that exe in selenium.
Process proc = Runtime.getRuntime().exec("C:\\farheen\\FileUpload.exe");
If you want to test this script then just download the script exe file and click on browse button on web page and run this exe file. Just make sure you have your file in correct path by changing this line of script in the second step
Local $file = "c:\yourpath\howtoupload.doc"
in above line of script change your file path then make exe of your script then click on browse button on your web page then run this exe . I am sure this would work.
Above script work for Firefox.Below for IE.
#include
; Internet Explorer is partly integrated in shell.application
$oShell = ObjCreate("shell.application") ; Get the Windows Shell Object
$oShellWindows=$oShell.windows ; Get the collection of open shell Windows
$MyIExplorer=""
for $Window in $oShellWindows ; Count all existing shell windows
; Note: Internet Explorer appends a slash to the URL in it's window name
if StringInStr($Window.LocationURL,"http://") then
$MyIExplorer=$Window
exitloop
endif
next
$oForm = _IEGetObjByName ($MyIExplorer, "UploadedFile")
_IEAction($oForm, "click")
WinActivate("File Upload");
Local $file = "c:\yourpath\howtoupload.doc"
ControlSetText("File Upload", "", "Edit1", $file )
ControlClick("File Upload", "", "Button2")
In above script you might need to change your file path and browse button name and the title of you dialog box.
Recently, I had the challenge of writing some automation for a workflow which included uploading a file because uloading a file works on windows component.
selenium is unable to access windows components and it will be handled through AutoIT.
Once you are able to click on browse button and a dialog box is open to choose the file then you just run a AutoIT script which will help to select the file from your local or remote drive and control will come to your web page to proceed with selenium.
Step to choose a file from your local or remote drive
Step 1.
Download the AutoIT and intall it.
Download AutoIT from its homepage
step 2.
write a AutoIT script to choose a file from your local or remote drive.
#include
; Internet Explorer is partly integrated in shell.application
$oShell = ObjCreate("shell.application") ; Get the Windows Shell Object
$oShellWindows=$oShell.windows ; Get the collection of open shell Windows
$MyIExplorer=""
for $Window in $oShellWindows ; Count all existing shell windows
; Note: Internet Explorer appends a slash to the URL in it's window name
if StringInStr($Window.LocationURL,"http://") then
$MyIExplorer=$Window
exitloop
endif
next
$oForm = _IEGetObjByName ($MyIExplorer, "UploadedFile")
_IEAction($oForm, "click")
WinActivate("Choose file");
Local $file = "C:\Documents and Settings\intelizen\Desktop\selenium.txt"
ControlSetText("Choose file", "", "Edit1", $file )
ControlClick("Choose file", "", "Button2")
setp 3.
Complie AutoIT script and make exe of that script.
Right click on that saved script file and click on "Compile script" from context menu. This will make an exe file of that script.
setp 4.
Call that exe in selenium.
Process proc = Runtime.getRuntime().exec("C:\\farheen\\FileUpload.exe");
If you want to test this script then just download the script exe file and click on browse button on web page and run this exe file. Just make sure you have your file in correct path by changing this line of script in the second step
Local $file = "c:\yourpath\howtoupload.doc"
in above line of script change your file path then make exe of your script then click on browse button on your web page then run this exe . I am sure this would work.
Above script work for Firefox.Below for IE.
#include
; Internet Explorer is partly integrated in shell.application
$oShell = ObjCreate("shell.application") ; Get the Windows Shell Object
$oShellWindows=$oShell.windows ; Get the collection of open shell Windows
$MyIExplorer=""
for $Window in $oShellWindows ; Count all existing shell windows
; Note: Internet Explorer appends a slash to the URL in it's window name
if StringInStr($Window.LocationURL,"http://") then
$MyIExplorer=$Window
exitloop
endif
next
$oForm = _IEGetObjByName ($MyIExplorer, "UploadedFile")
_IEAction($oForm, "click")
WinActivate("File Upload");
Local $file = "c:\yourpath\howtoupload.doc"
ControlSetText("File Upload", "", "Edit1", $file )
ControlClick("File Upload", "", "Button2")
In above script you might need to change your file path and browse button name and the title of you dialog box.
How to locate an element based on their label in selenium
Some time it difficult to locate an element usiing DOM, HTML and xpath. In that case we use to locate the element with the
help of their lables.
For example : Go to yahoo login page
selenium.open("https://login.yahoo.com");
Based on the lable "Yahoo ! ID" we will read the text box and type in.
selenium.type("css=label:contains(\"Yahoo! ID\")+input", "farheen");
Based on the lable "Password" we will locate the text box for password and type in.
selenium.type("css=label:contains(\"Password\")+input", "pass");
Go to yahoo registrantion page.
selenium.open("https://edit.yahoo.com/registration?.intl=us");
Based on Name label we will type in First Name text box.
selenium.type("css=label:contains(\"Name\")+div>input", "farheen");
Based on Name label we will type in Last name text box.
selenium.type("css=label:contains(\"Name\")+div>input+input", "khan");
Based on Gender lable we will select the gender from drop down.
selenium.select("css=label:contains(\"Gender\")+div>select", "label=Male");
Based on Birthday lable we will select the month from drop down.
selenium.select("css=label:contains(\"Birthday\")+div>select", "label=January");
Based on Birthday lable we will type the date in date text box.
selenium.type("css=label:contains(\"Birthday\")+div>select+input", "2");
Based on Birthday lable we will type the year in year text box.
selenium.type("css=label:contains(\"Birthday\")+div>select+input+input", "1982");
Based on country lable we will select India in country drop down box.
selenium.select("css=div>label:contains(\"Country\")+div>select",
"label=India");
+ Is used to point the element on the same node in tree of css.
to access firstname text box
selenium.type("css=label:contains(\"Name\")+div>input", "farheen");
to access secondname its the same label of div but on the second place
selenium.type("css=label:contains(\"Name\")+div>input+input", "khan");
> Is used to point the element one node down in the tree of css.
to access firstname text box
selenium.type("css=label:contains(\"Name\")+div>input", "farheen");
help of their lables.
For example : Go to yahoo login page
selenium.open("https://login.yahoo.com");
Based on the lable "Yahoo ! ID" we will read the text box and type in.
selenium.type("css=label:contains(\"Yahoo! ID\")+input", "farheen");
Based on the lable "Password" we will locate the text box for password and type in.
selenium.type("css=label:contains(\"Password\")+input", "pass");
Go to yahoo registrantion page.
selenium.open("https://edit.yahoo.com/registration?.intl=us");
Based on Name label we will type in First Name text box.
selenium.type("css=label:contains(\"Name\")+div>input", "farheen");
Based on Name label we will type in Last name text box.
selenium.type("css=label:contains(\"Name\")+div>input+input", "khan");
Based on Gender lable we will select the gender from drop down.
selenium.select("css=label:contains(\"Gender\")+div>select", "label=Male");
Based on Birthday lable we will select the month from drop down.
selenium.select("css=label:contains(\"Birthday\")+div>select", "label=January");
Based on Birthday lable we will type the date in date text box.
selenium.type("css=label:contains(\"Birthday\")+div>select+input", "2");
Based on Birthday lable we will type the year in year text box.
selenium.type("css=label:contains(\"Birthday\")+div>select+input+input", "1982");
Based on country lable we will select India in country drop down box.
selenium.select("css=div>label:contains(\"Country\")+div>select",
"label=India");
+ Is used to point the element on the same node in tree of css.
to access firstname text box
selenium.type("css=label:contains(\"Name\")+div>input", "farheen");
to access secondname its the same label of div but on the second place
selenium.type("css=label:contains(\"Name\")+div>input+input", "khan");
> Is used to point the element one node down in the tree of css.
to access firstname text box
selenium.type("css=label:contains(\"Name\")+div>input", "farheen");
How to use CSS in Selenium to locate an element
XPath locator is one of the most precise locator. But this has a disadvantage of its locator types thats is its slowness.
This disadvantage of xpath you can see when running the tests under IE while Firefox works with xpath pretty faster than IE.
The main thing is that tests which intensively use XPath work extremely slow under IE and this feature is the cause of huge variety of problems related to execution speed as well as quality of the tests itself especially during operations with dynamic content.
For this reason CSS locators can be good alternative of XPath. What can we do with CSS locators?
CSS locator will give you clear picture of your element hierarchy
lets say your xpath of an element is like,
xpath=//div//span/a
the same locatore can be identified by CSS is .
css=div * span > a
from the above example there are two symbol are being used to locate an element.
1) "/" in xpath is just a next level of DOM element hierarchy and same used in CSS is ">"
2) "//" in xpath is any DOM object hierarchy level under current object and same used in CSS is "*"
The way we use attributes in xpath we can use attributes in css as well. lets say your element's xpath is like this
//input[@name='continue' and @type='button']
can be written in CSS
css=input[name='continue'][type='button']
or
css=input[name=continue][type=button]
in xpath we can check the partial attribute value matching but in CSS we can't.
lets say your element is like this
so the xpath to locate this element is .
xpath=//div[contains(@title,"title")]
and same can be used in CSS like
css=div[title~=title]
But if your element is like this
then CSS locator css=div[title~=title] wont work here .
CSS provides us the easy way to specify the element.
lets say your element is like this,
we can write in xpath like this
xpath=//input[@id="username"]
and same can be specified in CSS
css=input#username
so whenever we want to identify any element with their id then we use #
lets say your element is like this,
then xpath is
xpath=//input[@class="password"]
and corresponding CSS is
css=input.password
so whenever we want to identify any element with their class then we use .
below are the element sturcture used in above examples.
An interesting feature of CSS in Selenium :Sub-String matches.
^= Match a prefix
$= Match a suffix
*= Match a substring
1 css=a[id^='id_prefix_']
A link with an “id” that starts with the text “id_prefix_”
2 css=a[id$='_id_sufix']
A link with an “id” that ends with the text “_id_sufix”
3 css=a[id*='id_pattern']
A link with an “id” that contains the text “id_pattern”
these CSS features are awesome more details can be found on
How to use CSS in Selenium extensively
and if you want to know in depth then visit this page.
http://www.w3.org/TR/css3-selectors/
This disadvantage of xpath you can see when running the tests under IE while Firefox works with xpath pretty faster than IE.
The main thing is that tests which intensively use XPath work extremely slow under IE and this feature is the cause of huge variety of problems related to execution speed as well as quality of the tests itself especially during operations with dynamic content.
For this reason CSS locators can be good alternative of XPath. What can we do with CSS locators?
CSS locator will give you clear picture of your element hierarchy
lets say your xpath of an element is like,
xpath=//div//span/a
the same locatore can be identified by CSS is .
css=div * span > a
from the above example there are two symbol are being used to locate an element.
1) "/" in xpath is just a next level of DOM element hierarchy and same used in CSS is ">"
2) "//" in xpath is any DOM object hierarchy level under current object and same used in CSS is "*"
The way we use attributes in xpath we can use attributes in css as well. lets say your element's xpath is like this
//input[@name='continue' and @type='button']
can be written in CSS
css=input[name='continue'][type='button']
or
css=input[name=continue][type=button]
in xpath we can check the partial attribute value matching but in CSS we can't.
lets say your element is like this
so the xpath to locate this element is .
xpath=//div[contains(@title,"title")]
and same can be used in CSS like
css=div[title~=title]
But if your element is like this
then CSS locator css=div[title~=title] wont work here .
CSS provides us the easy way to specify the element.
lets say your element is like this,
we can write in xpath like this
xpath=//input[@id="username"]
and same can be specified in CSS
css=input#username
so whenever we want to identify any element with their id then we use #
lets say your element is like this,
then xpath is
xpath=//input[@class="password"]
and corresponding CSS is
css=input.password
so whenever we want to identify any element with their class then we use .
below are the element sturcture used in above examples.
An interesting feature of CSS in Selenium :Sub-String matches.
^= Match a prefix
$= Match a suffix
*= Match a substring
1 css=a[id^='id_prefix_']
A link with an “id” that starts with the text “id_prefix_”
2 css=a[id$='_id_sufix']
A link with an “id” that ends with the text “_id_sufix”
3 css=a[id*='id_pattern']
A link with an “id” that contains the text “id_pattern”
these CSS features are awesome more details can be found on
How to use CSS in Selenium extensively
and if you want to know in depth then visit this page.
http://www.w3.org/TR/css3-selectors/
How to verify value in drop down list.
Take an example How to find some value is in drop down list or now? To find element drop down is easy but to find a drop down having some specific
value in their list is difficult.
Go to www.ebay.in you will see there is drop down along with search text box.
How to veify a specific value "Collectibles" is in drop down list.
Using Xpath:
verifyElementPresent
//select[@id='_sacat']/option[contains(text(),'Collectibles')]
verifyTrue(selenium.isElementPresent("//select[@id='_sacat']/option[contains(text(),'Collectibles')]"));
Using CSS:
verifyElementPresent
css=select#_sacat>option:contains("Fun")
verifyTrue(selenium.isElementPresent("css=select#_sacat>option:contains(\"Fun\")"));
verifyElementPresent
css=select>option:contains("Fun")
value in their list is difficult.
Go to www.ebay.in you will see there is drop down along with search text box.
How to veify a specific value "Collectibles" is in drop down list.
Using Xpath:
verifyTrue(selenium.isElementPresent("//select[@id='_sacat']/option[contains(text(),'Collectibles')]"));
Using CSS:
verifyTrue(selenium.isElementPresent("css=select#_sacat>option:contains(\"Fun\")"));
Subscribe to:
Posts (Atom)