Example One: The main difference is the inclusion of the WebDriver API into Selenium. I’ve put together a small example below that uses the new API to log into two web based e-mail clients and send an e-mail. WebDriverTestBase.java package tests; import import import import import import import
org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver; org.openqa.selenium.support.ui.Wait; org.openqa.selenium.support.ui.WebDriverWait; org.testng.Assert; org.testng.annotations.AfterClass; org.testng.annotations.BeforeClass;
public class WebDriverTestBase { public static FirefoxDriver driver; public static Wait wait; @BeforeClass(alwaysRun = true) protected void startWebDriver() { driver = new FirefoxDriver(); wait = new WebDriverWait(driver, 120); } @AfterClass(alwaysRun = true) protected void closeSession() { driver.close(); } public static void assertEquals(Object actual, Object expected) { Assert.assertEquals(actual, expected); }
} VisibilityOfElementLocated.java package tests; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; public class VisibilityOfElementLocated implements ExpectedCondition { By findCondition; VisibilityOfElementLocated(By by) { this.findCondition = by; } public Boolean apply(WebDriver driver) { driver.findElement(this.findCondition); return Boolean.valueOf(true); } } WebmailTest.java package tests; import org.openqa.selenium.By; import org.testng.annotations.Test; public class WebmailTest extends WebDriverTestBase { //variables public static final String YAHOO_EMAIL = "
[email protected]"; public static final String HOTMAIL_EMAIL = "
[email protected]";
@Test(description = "Sends an e-mail from Yahoo account") public void sendFromYahoo() { //new message variables String to = HOTMAIL_EMAIL; String subject = "Test Sending Email Message From Yahoo"; String message = "This is a test e-mail from Yahoo"; //login to yahoo driver.get("http://mail.yahoo.com/"); driver.findElement(By.id("username")).sendKeys(YAHOO_EMAIL); driver.findElement(By.id("passwd")).sendKeys("mytestpw"); driver.findElement(By.id(".save")).click(); //create new message driver.findElement(By.id("compose_button_label")).click(); wait.until(new VisibilityOfElementLocated(By.xpath("id('_testTo_label')/ancestor::tr[1]//textare a"))); //send test message
driver.findElement(By.xpath("id('_testTo_label')/ancestor::tr[1]//textarea")).sendKeys( to);
driver.findElement(By.xpath("id('_testSubject_label')/ancestor::tr[1]//input")).sendKeys (subject); driver.switchTo().frame("compArea_test_"); driver.findElement(By.xpath("//div")).sendKeys(message); driver.switchTo().defaultContent(); driver.findElement(By.id("SendMessageButton_label")).click(); //WARNING! sometimes a captcha is displayed here wait.until(new VisibilityOfElementLocated(By.xpath("//nobr[contains(text(), 'Message Sent')]")));
} @Test(description = "Sends an e-mail from Hotmail account") public void sendFromHotmail() { //new message variables String to = YAHOO_EMAIL; String subject = "Test Sending Email Message From Hotmail"; String message = "This is a test e-mail from Hotmail"; //login to hotmail driver.get("http://mail.live.com/"); driver.findElement(By.name("login")).sendKeys(HOTMAIL_EMAIL); driver.findElement(By.name("passwd")).sendKeys("mytestpw"); if (driver.findElement(By.name("remMe")).isSelected()) { driver.findElement(By.name("remMe")).click(); } driver.findElement(By.name("SI")).click(); //create new message driver.switchTo().frame("UIFrame"); driver.findElement(By.id("NewMessage")).click(); //send test message driver.findElement(By.id("AutoCompleteTo$InputBox")).sendKeys(to); driver.findElement(By.id("fSubject")).sendKeys(subject); driver.switchTo().frame("UIFrame.1"); driver.findElement(By.xpath("//body")).sendKeys(message); driver.switchTo().frame("UIFrame"); driver.findElement(By.id("SendMessage")).click();
assertEquals(driver.findElement(By.cssSelector("h1.SmcHeaderColor")).getTex t(), "Your message has been sent"); } }
Example Two: Window Handle example with selenium webdriver + using Java - The Set Interface for selenium automation testing package testngtest; import java.util.Iterator; import java.util.Set; import import import import import import
org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver; org.testng.annotations.Test; org.testng.annotations.BeforeMethod; org.testng.annotations.AfterMethod;
public class TestNG_WindowHandleExample_by_jasmine { // Declare global test varialbles WebDriver jasminedriver = new FirefoxDriver(); String Open_a_popup_window; String Positioned_Popup; String JavaScript_Popup_Windows; @Test public void f() throws InterruptedException { // A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. Set windowids = jasminedriver.getWindowHandles(); //iterator( ) //Returns an Iterator object for the collection which may be used to retrieve an object
Iterator iter= windowids.iterator(); JavaScript_Popup_Windows=iter.next(); // Open first popup jasminedriver.findElement(By.xpath("//*[@id='content']/div[3]/a") ).click(); windowids = jasminedriver.getWindowHandles(); iter= windowids.iterator(); iter.next(); Open_a_popup_window=iter.next(); System.out.println(JavaScript_Popup_Windows); System.out.println(Open_a_popup_window); Thread.sleep(3000L); System.out.println(); System.out.println("Positioned_Popup"); // switch to main window to click on other popup link jasminedriver.switchTo().window(JavaScript_Popup_Wind ows); // Open second popup jasminedriver.findElement(By.xpath("//*[@id='content']/d iv[5]/p/a")).click(); windowids = jasminedriver.getWindowHandles(); iter= windowids.iterator(); iter.next(); iter.next(); Positioned_Popup = iter.next(); System.out.println(JavaScript_Popup_Windows); System.out.println(Open_a_popup_window); System.out.println(Positioned_Popup); System.out.println();
Thread.sleep(3000L); System.out.println("Centered_Popup"); } @BeforeMethod public void beforeMethod() { jasminedriver.get("http://www.quackit.com/javascript/popup_win dows.cfm"); } @AfterMethod public void afterMethod() { jasminedriver.switchTo().window(Open_a_popup_window); jasminedriver.close(); jasminedriver.switchTo().window(Positioned_Popup); jasminedriver.close();
jasminedriver.switchTo().window(JavaScript_Popup_Windows); jasminedriver.quit(); } } Example Three: In Selenium 2(WebDriver), testing popup windows involve switching the driver to the popup window and then running the corresponding actions. Twist recorder records actions in popup windows as commented code. For eg.
//Write your logic to locate the appropriate popup before using commented actions. //Look at - 'How do I handle popup in WebDriver' section for more details. //action in popup "Google". popup.findElement(By.name("q")).sendKeys("Thoughtworks"); //action in popup "Google". popup.findElement(By.name("btnG")).submit();"
The above code is the result of recording in the popup window having google search page, searching for "Thoughtworks". To get the above code working: 1) Identify the popup, The following code identifies the popup window with title "Google". Note that the actions tells the title of the popup window. Add the code just before the first popup action being commented. String parentWindowHandle = browser.getWindowHandle(); // save the current window handle. WebDriver popup = null; Iterator windowIterator = browser.getWindowHandles(); while(windowIterator.hasNext()) { String windowHandle = windowIterator.next();
popup = browser.switchTo().window(windowHandle); if (popup.getTitle().equals("Google") { break; } }
2) Uncomment code for the same popup, //action in popup "Google". popup.findElement(By.name("q")).sendKeys("Thoughtworks"); //action in popup "Google". popup.findElement(By.name("btnG")).submit();"
3) After the popup actions, switch the driver back to the parent window, browser.close(); // close the popup. browser.switchTo().window(parentWindowHandle); // Switch back to parent window.
Example Four:
Creating a test suite using Selenium 2 / Webdriver After writing my post: HYPERLINK "http://ncona.com/2012/02/running-selenium-2-webdrivertests/" \o "Running Selenium 2.0 / Webdriver tests" Running Selenium 2.0 / Webdriver tests, I was thinking how could I make a test suite so I could run all my functional tests with just one command. In this post I am going to explain how I used Java classes to do this. This post is highly based on HYPERLINK "http://ncona.com/2012/02/running-selenium-2-webdrivertests/" \o "Running Selenium 2.0 / Webdriver tests" Running Selenium 2.0 / Webdriver tests, so if you feel you don’t understand what I am saying, please read that post first. Test Suite The first thing I figured is that we need a main class that will call all the other classes tests, so I created a main test suite file called NconaTestSuite.java with this content: 1package com.ncona; 2 3import org.openqa.selenium. 4WebDriver; 5import org.openqa.selenium.fi 6refox.FirefoxDriver; 7import org.openqa.selenium.s 8upport.ui.Wait; 9import org.openqa.selenium.s 10upport.ui.WebDriverWait; 11 12public class NconaTestSuite 13{ 14 15 public static void main( HYPE 16RLINK 17"http://www.google.com/searc 18h?hl=en&q=allinurl 19%3Astring+java.sun.com&btnI
20=I%27m%20Feeling 21%20Lucky" String[] args) 22 { 23 // Objects that are going 24to be passed to all test classes 25 WebDriver 26driver = new FirefoxDriver(); 27 28Waitwait = new 29WebDriverWait(driver, 30); 30 31 boolean result; 32 try 33 { 34 // Here we add all the 35test classes we want to run 36 MiscTestClass 37mtc1 = new MiscTestClass(); 38 MiscTestClassTwo 39mtc2 = new MiscTestClassTw 40o(); 41 MiscTestClassThree 42mtc3 = new MiscTestClassThr 43ee(); 44 45 // We call the run 46method (that method runs all 47 // the tests of the 48class) for each of the classes 49 // above. If any test fails result will be false. result = ( mtc1.run(driver, wait) && mtc2.run(driver, wait) && mtc3.run(driver, wait)
) } catch ( HYPERLINK "http://www.google.com/searc h?hl=en&q=allinurl %3Aexception+java.sun.com &btnI=I%27m%20Feeling %20Lucky" Exception e) { e.printStackTrace(); result = false; } finally { driver.close(); } HYPERLINK "http://www.google.com/searc h?hl=en&q=allinurl %3Asystem+java.sun.com&bt nI=I%27m%20Feeling %20Lucky" System.out.println("Test " + (result ? "passed." : "failed .")); if (!result) { HYPERLINK "http://www.google.com/searc h?hl=en&q=allinurl %3Asystem+java.sun.com&bt nI=I%27m%20Feeling %20Lucky" System.exit(1); } } } Test Class
Our test classes need to have a run method that will run all the tests it contains. Here is an example of how it could look: 1package com.ncona; 2 3import java.util.List; 4import org.openqa.selenium.B 5y; 6import org.openqa.selenium. 7WebDriver; 8import org.openqa.selenium. 9WebElement; 10import org.openqa.selenium.fi 11refox.FirefoxDriver; 12import org.openqa.selenium.s 13upport.ui.ExpectedCondition; 14import org.openqa.selenium.s 15upport.ui.Wait; 16import org.openqa.selenium.s 17upport.ui.WebDriverWait; 18 19public class MiscTestClass 20{ 21 static WebDriver driver; 22 23 static Wait wait 24; 25 26 27 public static boolean run(We 28bDriver driverArg, 29Wait waitArg) 30 { 31 driver = driverArg; 32 wait = waitArg; 33 34 setUp(); 35
36 // Run all the methods 37and return false if any fails 38 return ( 39 miscMethod() 40 && miscMethod2() 41 ); 42 } 43 44 private static boolean miscM ethod() { // Put your tests code here return result } private static boolean miscM ethod2() { // Put your tests code here return result } } Build file The build.xml file used for this test suite almost the same as the one in my previous post. We just need to change the target to use the name of our new test suite file: 1 3 4
6 7 11 12 14 15 17 18 22 23 24 26 28 29 30 31 32 Run the suite First we need to build the project: 1ant build Finally to run it we would use this command: 1ant run-example -Dexample=NconaTestSuite Example Five:
Selenium WebDriver, Selenium Server and PageObjects by Example HYPERLINK "http://www.hascode.com/2012/03/selenium-webdriver-seleniumserver-and-pageobjects-by-example/" http://www.hascode.com/2012/03/seleniumwebdriver-selenium-server-and-pageobjects-by-example/
Example Six: HYPERLINK "http://seleniumforum.forumotion.net/t1031-needselenium-webdriver-excel-sheet-examples" Selenium Webdriver + Excel sheet examples Example for read/write operations from excel sheet using selenium webdriver. import jxl.Sheet; import jxl.Workbook; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.io.FileInputStream; import java.io.IOException; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class TestData{ WebDriver driver = new ChromeDriver(); public void Login() throws InterruptedException, BiffException, IOException {
FileInputStream fi=new FileInputStream("D:\\sreeworkspace\\sree.xls"); Workbook workbook = Workbook.getWorkbook(fi); Sheet sheet = workbook.getSheet("Login"); String s=sheet.getCell(2,2).getContents(); System.out.println(s); driver.findElement(By.id("gbqfq")).sendKeys(s); driver.findElement(By.name("btnK")).click(); } public static void main(String[] args) throws InterruptedException, BiffException, IOException { System.setProperty("webdriver.chrome.driver", "D:/sreekumar/Tutorial/Selenium/chromedriver_win_18.0.995.0/ chromedriver.exe"); //Pausing here seems to make it work better, so... TestData login = new TestData(); login.driver.get("https://www.google.com"); login.Login(); } } Example Seven: Uploading Files in Remote WebDriver March 8th, 2012 by Santiago Suarez Ordoñez Since it’s been a while since my last Selenium tips blog post, I thought it was time to share some Selenium love again. Today we’re covering WebDriver’s native solution to a very common issue when doing distributed cross browser testing: uploading files in remote servers.
As you may know, the way to address this in Selenium 1 is to place your files in an accessible web server and use the attachFile command that points to the correct URL. With Selenium 2, the Selenium Dev team has luckily made this a lot more straightforward. For those of you doing this locally, all you need to do is use the sendKeys command totype the local path of the file in any file field. This works like a charm in all drivers. When moving this test to a remote server (such as, for example, our Selenium 2 Cloud), all you need to do is use the setFileDetector method to let WebDriver know that you’re uploading files from your local computer to a remote server instead of just typing a path. Almost magically, the file will be base64 encoded and sent transparentlythrough the JSONWireProtocol for you before writing the fixed remote path. This is an excellent solution, as it lets you switch your tests from a local to remote Driver without having to worry about changing your tests’ code. This feature is available in all the official Selenium 2 bindings, just make sure Selenium 2.8.0 or newer is used as this feature has been released then. Here are some examples tests: Java import import import import import import
junit.framework.Assert; junit.framework.TestCase; org.openqa.selenium.*; org.openqa.selenium.remote.*; java.net.URL; java.util.concurrent.TimeUnit;
public class TestingUploadSe2Sauce extends TestCase { private RemoteWebDriver driver; public void setUp() throws Exception { DesiredCapabilities capabillities = DesiredCapabilities.firefox(); capabillities.setCapability("version", "7"); capabillities.setCapability("platform", Platform.XP); capabillities.setCapability("selenium-version", "2.18.0"); capabillities.setCapability("name", "Remote File Upload using Selenium 2's FileDetectors");
driver = new RemoteWebDriver( new URL("http://:@ondemand.saucelabs.com:80/wd/hub"), capabillities); driver.setFileDetector(new LocalFileDetector()); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } public void testSauce() throws Exception { driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload"); WebElement upload = driver.findElement(By.id("myfile")); upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg"); driver.findElement(By.id("submit")).click(); driver.findElement(By.tagName("img")); Assert.assertEquals("darkbulb.jpg (image/jpeg)", driver.findElement(By.tagName("p")).getText()); } public void tearDown() throws Exception { driver.quit(); } } __________________________________________________________________ ________________ Example Eight: Selenium Grid with WebDriver I had earlier covered in my blog on how to execute your RC cases in selenium grid. But with the commencement of Selenium2/Webdriver, grid setup has been changed. In the following blog I will cover how to set-up your grid and the changes that will be required for easy execution of cases. Following things are required:
1. Selenium 2.xx version server jar and Java library. The latest one can be downloaded from the link: HYPERLINK "http://code.google.com/p/selenium/downloads/list" Selenium-2 2. Java 1.6 and above 3. TestNg jar . You can download it from the link: HYPERLINK "http://testng.org/doc/download.html" TestNG 4. Eclipse with TestNG plugin installed(optional) 5. ChromeDriver. Can be downloaded from: HYPERLINK "http://code.google.com/p/chromium/downloads/list" ChromeDriver The Test Code Following is an example of test-class that have a test case to search google for "testing" and verifying after clicking it on a link. HYPERLINK "http://blog.varunin.com/2011/10/selenium-grid-withwebdriver.html" ? import 1 java.net.MalformedURLExce 2 ption; 3 import java.net.URL; 4 5 import 6 org.openqa.selenium.WebDr 7 iver; 8 import 9 org.openqa.selenium.WebDr 10 iverBackedSelenium; 11 import 12 org.openqa.selenium.remot 13 e.DesiredCapabilities; 14 import 15 org.openqa.selenium.remot 16 e.RemoteWebDriver; 17 import 18 org.testng.annotations.Af 19 terClass; 20 import 21
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
org.testng.annotations.Be foreClass; import org.testng.annotations.Pa rameters; import org.testng.annotations.Te st; import com.thoughtworks.selenium .Selenium; import junit.framework.Assert; public class Google { private Selenium selenium; @Parameters({"browser"," port"}) @BeforeClass public void beforeClass(String browser,String port){ DesiredCapabilities capability= new DesiredCapabilities(); capability.setBrowserNa me(browser); try { WebDriver driver= new RemoteWebDriver(new URL(" HYPERLINK "http://localhost/" http://localhost:".concat (port).concat("/wd/hub")) , capability); selenium = new WebDriverBackedSelenium(d
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
river, " HYPERLINK "http://www.google.com/" http://www.google.com"); } catch (MalformedURLException e) { }
e.printStackTrace();
} @Test public void search() { selenium.open("/"); selenium.type("id=lstib", "testing"); selenium.click("//input [@value='Google Search']"); for (int second = 0;; second++) { if (second >= 60) Assert.fail("timeout" ); try { if (selenium .isElementPresent(" link=Software testing Wikipedia, the free encyclopedia")) break; } catch (Exception e) { } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Autogenerated catch block
e.printStackTrace();
}
} selenium.click("link=So ftware testing Wikipedia, the free encyclopedia"); for (int second = 0;; second++) { if (second >= 60) Assert.fail("timeout" ); try { if (selenium.isTextPresent(" Software testing")) break; } catch (Exception e) { } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace();
} }
} @AfterClass public void afterClass(){ selenium.stop(); } } In the above class I am using the TestNG "Parameter" property to provide different data set to the "BeforeClass" method "beforeClass". The beforeClass method accepts two properties "browser" and a "port". These values are used for initialization of driver and in-turn for
initialization of selenium object. In the above code I am using the "WebDriverBackedSelenium" class for creation of the selenium object, so that its easy for guys who had worked on Selenium-1 to understand the code. If you want the code to be purely WebDriver, you can directly use the "driver" object for defining your test-cases. The main part in this test case is how the driver object is being created: DesiredCapabilities capability= new DesiredCapabilities(); capability.setBrowserName(browser); WebDriver driver= new RemoteWebDriver(new URL("http://localhost:".concat(port).concat("/wd/hub")) , capability); The above code creates an object of DesiredCapability and then set the browser value to it. Now using this "capability" object I am creating the webdriver object using the "RemoteWebDriver" class. This tells the selenium on which browser the test-case needs to run and where the server is located. In this example I am assuming the server to be running locally. In case it is on different system the "localhost" needs to be re-placed with the ip of the said system. TestNG configuration For parallel execution you need to use the TestNG configuration. Following is an "testng.xml" file for the above said test class. The said configuration executes the test-cases across different browser.
In the above configuration, I am configuring TestNG to run "tests" in parallel. Also there are two different tests inside a suite. For each test a different "browser" parameter value has been configured. Selenium-Grid server Now start your grid using the following commands. Run each command in a seperate terminal or command prompt by going to the directory containing your selenium-server-standalone-2.x.x.jar. In the following example I am using the 2.7.0 version of selenium. For Hub: java -jar selenium-server-standalone-2.7.0.jar -role hub For a firefox based node: java -jar selenium-server-standalone-2.7.0.jar -role webdriver -hub http://localhost:4444/grid/register -port 5556 -browser browserName=firefox For google-chrome based node:
java -Dwebdriver.chrome.driver=/path/to/chromedriver -jar selenium-server-standalone-2.7.0.jar -role webdriver -hub http://localhost:4444/grid/register -port 5555 -browser browserName=chrome Before running the above command you need to provide the chrome-driver path to the property "-Dwebdriver.chrome.driver". Now run your testng.xml from eclipse by selecting it -> Right click -> Run as -> TestNG suite(this will work only if you have TestNG plugin installed in your eclipse.) Or you can choose other ways to execute "testng.xml" like from command prompt, using ant or maven. Once you run the above testng.xml. TestNG will execute the cases from the Google class on grid across different browsers firefox and google-chrome as configured. You can do configurations for environment like OS (Linux,Windows), browser, browser-version and all and then you can run you cases on particular type of environment by configuring them accordingly. More details can be found at the following URL: HYPERLINK "http://code.google.com/p/selenium/wiki/Grid2" http://code.google.com/p/selenium/wiki/Grid2 Example Nine: Data-Driven testing using Junit and TestNG Most of the guys who are into automation may be knowing the term Data-Driven testing. But the word will still be new for some fresh faces in the field of automation. In this blog I will explain what is Data-Driven testing and will give an example of Datadriven testing using Junit and TestNG frameworks. Data-Driven testing as the name suggests is a test driven by the Data. For ex. You have a user detail form where you need to
enter details of multiple users and save them. Here if you have 5 different user data available and you have to write automation cases for these, you may end up writing 5 different automation test cases(one for each user data). If you apply a Data-Driven approach you will end up with only one test-case, that is filling the form with user data and then submitting it. The test case will get executed based on the data provided to it. In this case it will be 5 and hence the test case will get executed 5 times with different data-set. The advantage of using a Data-driven approach is that you reduce your effort in writing/maintaing test-cases for your different type of data. In case of additions or deletion of new/old entries , you just have to change the data and not your actual test-case. Following I will mention a Data-Driven approach for searching on google with different data using Junit and TestNg frameworks: Using Junit: HYPERLINK "http://blog.varunin.com/2011/10/data-driven-testingusing-junit-and.html" ? import static 1 org.junit.Assert.fail; 2 3 import 4 com.thoughtworks.selenium 5 .*; 6 import org.junit.After; 7 import org.junit.Before; 8 import org.junit.Test; 9 10 import 11 org.junit.runner.RunWith; 12 import 13 org.junit.runners.Paramet 14 erized; 15 import 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
org.junit.runners.Paramet erized.Parameters; import org.openqa.selenium.WebDr iver; import org.openqa.selenium.WebDr iverBackedSelenium; import org.openqa.selenium.firef ox.FirefoxDriver; import java.util.Arrays; import java.util.List; @RunWith(Parameterized.cl ass) public class JunitGoogleBase { public Selenium selenium; WebDriver driver; private String testData; public JunitGoogleBase(String testData){ this.testData=testData ; } @Parameters public static List< Object[]> data() { return Arrays.asList(new Object[] []{{"testing"},{"Software testing"}}); }
57 58 59 60 61 62 63 64
@Before public void setUp() throws Exception { driver= new FirefoxDriver(); selenium = new WebDriverBackedSelenium(d river, " HYPERLINK "http://www.google.com/" http://www.google.com"); selenium.open(" HYPERLINK "http://www.google.com/" http://www.google.com"); } @Test public void testSearch() throws Exception { selenium.open("/"); selenium.type("id=lstib", testData); selenium.click("//inpu t[@value='Google Search']"); for (int second = 0;; second++) { if (second >= 60) fail("timeout"); try { if (selenium.isElementPresen t("link=Software testing - Wikipedia, the free encyclopedia")) break; } catch (Exception e) {} Thread.sleep(1000); } selenium.click("link=S oftware testing Wikipedia, the free
encyclopedia"); for (int second = 0;; second++) { if (second >= 60) fail("timeout"); try { if (selenium.isTextPresent(" Software testing")) break; } catch (Exception e) {} Thread.sleep(1000); } } @After public void tearDown() throws Exception { selenium.stop(); } } Using TestNg: HYPERLINK "http://blog.varunin.com/2011/10/data-driven-testingusing-junit-and.html" ? import 1 com.thoughtworks.selenium 2 .*; 3 4 5 import 6 org.openqa.selenium.WebDr 7 iver; 8 import 9 org.openqa.selenium.WebDr 10 iverBackedSelenium; 11 import 12 org.openqa.selenium.firef 13
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
ox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.Af terMethod; import org.testng.annotations.Be foreMethod; import org.testng.annotations.Da taProvider; import org.testng.annotations.Te st;
public class TestNGGoogleBase { public Selenium selenium; WebDriver driver; @DataProvider(name="par ameter") public static Object[] [] data() { return new Object[][] {{"testing"},{"Software testing"}}; } @BeforeMethod public void setUp() throws Exception { driver= new FirefoxDriver(); selenium = new WebDriverBackedSelenium(d river, " HYPERLINK
54 55 56
"http://www.google.com/" http://www.google.com"); selenium.open(" HYPERLINK "http://www.google.com/" http://www.google.com"); } @Test(dataProvider="par ameter") public void testSearch(String testData) throws Exception { selenium.open("/"); selenium.type("id=lstib", testData); selenium.click("//inpu t[@value='Google Search']"); for (int second = 0;; second++) { if (second >= 60) Assert.fail("timeout"); try { if (selenium.isElementPresen t("link=Software testing - Wikipedia, the free encyclopedia")) break; } catch (Exception e) {} Thread.sleep(1000); } selenium.click("link=S oftware testing Wikipedia, the free encyclopedia"); for (int second = 0;; second++) { if (second >= 60) Assert.fail("timeout");
try { if (selenium.isTextPresent(" Software testing")) break; } catch (Exception e) {} Thread.sleep(1000); } } @AfterMethod public void tearDown() throws Exception { selenium.stop(); } } The main difference in the above two functions is that you provide a Paramaterized option to the class in Junit and supply data to the constructor of the said class. Where as in TestNG you do the same at the test-method level. Its simple to do data-driven testing in TestNG framework as you can provide a different data providing function for each testmethod, but the same is not possible in Junit. Example Ten: HYPERLINK "http://blog.varunin.com/2010/05/generating-seleniumreports-using.html" Generating selenium reports using TestNG-xslt through Ant TestNG-xslt generates user friendly reports using the TestNG results output (testng-results.xml). Its uses the pure XSL for report generation and Saxon as an XSL2.0 implementation.
Most of the material is taken from the original site. http://code.google.com/p/testng-xslt/ I will tell in this blog how to implement this report for your project. This implementation will tell you how to generate the testng-xslt report using ant. If your current project does not use ant build then you can use ant only for the report generation purpose. If you dont know ant please check the Apache ant website http://ant.apache.org/. For generating testng-xslt report for your project do the following: 1. Download the testng-xslt 2. Unzip and copy the testng-results.xsl from the testng-xslt folder(testng-xslt-1.1\src\main\resources) to your own project folder. 3. Now copy the saxon library from (testng-xslt-1.1\lib\saxon8.7.jar)to your project lib folder. 4. Modify your build.xml of ant and add the following target to it. HYPERLINK "http://blog.varunin.com/search/label/Selenium %20Reports" ? 2 4 6 8 10 12 The XSL transformation can be configured using the parameters described below. testNgXslt.outputDir - Sets the target output directory for the HTML content. This is mandatory and must be an absolute path. If you are using the Maven plugin this is set automatically so you don't have to provide it. testNgXslt.cssFile - Specifies and alternative style sheet file overriding the default settings. This parameter is not required. testNgXslt.showRuntimeTotals - Boolean flag indicating if the report should display the aggregated information about the methods durations. The information is displayed for each test case and aggregated for the whole suite. Non-mandatory parameter, defaults to false. testNgXslt.reportTitle - Use this setting to specify a title for your HTML reports. This is not a mandatory parameter and defaults to "TestNG Results". testNgXslt.sortTestCaseLinks - Indicates whether the test case links (buttons) in the left frame should be sorted alphabetically. By default they are rendered in the order they are generated by TestNG so you should set this to true to change this behavior. testNgXslt.chartScaleFactor - A scale factor for the SVG pie chart in case you want it larger or smaller. Defaults to 1. testNgXslt.testDetailsFilter - Specified the default settings for the checkbox filters at the top of the test details page. Can be any combination (comma-separated) of:
FAIL,PASS,SKIP,CONF,BY_CLASS You need to provide the testng-xslt stylesheet the TestNG results xml(testng-results.xml) , the path to the style sheet testngresults.xsl and the output index.html path. Also dont forget to add the saxon library to your target classpath else you will get an error. In my case it is the master-classpath. Noe run the ant target for report generation (in my case "testngxslt-report") and check the ouput folder configured by you for testng-xslt report. Example Eleven: How to take a screenshot at the end of your Selenium WebDriver tests? INCLUDEPICTURE "http://www.muhuk.com/wpcontent/uploads/2012/02/webdriver_screenshot-300x270.png" \* MERGEFORMATINET When you run HYPERLINK "http://seleniumhq.org/" Selenium headless on the server, debugging failures with just the standard outputs can be challenging. A screenshot of the last state of the browser helps in this case. This little tutorial explains how to take such a screenshot and save it as an artifact in Jenkins. I will be using HYPERLINK "http://www.junit.org/" junit as the test framework. Step 0: Getting the name of the current test You probably want to include the name of the test class and the name of the current test method in the filename. Here is how you find it out: import org.junit.After; import org.junit.Rule; import org.junit.rules.TestName;
public abstract class Test { @Rule public TestName testName = new TestName(); @After public void tearDown() { String className = this.getClass().getSimpleName(); String methodName = this.testName.getMethodName(); System.err.println("Finished test " + className + "." + methodName + "()"); } } The code above is just a simple demonstration of how you use TestName. However it is a good idea to produce a simple output like above in the beginning and the end of each test. Step 1: Taking the screenshot HYPERLINK "http://seleniumhq.org/docs/04_webdriver_advanced.html" \l "taking-a-screenshot" Selenium documentation suggests the following: import org.junit.After; import java.io.File; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; public abstract class Test { @After public void tearDown() { // driver is your WebDriver File screenshot = ((TakesScreenshot) driver) .getScreenshotAs(OutputType.FILE);
}
}
Example code in the official documentation is a little more terse, I left out everything but the essentials. Step 2: Saving the image getScreenshotAs() method saves the output in a temporary location. I took HYPERLINK "http://stackoverflow.com/a/3423347/42188" the advice here and used FileUtils.copyFile() to copy this temporary file back inside my workspace. import org.junit.After; import java.io.IOException; import org.apache.commons.io.FileUtils; public abstract class Test { @After public void tearDown() { // screenshot is the file we have acquired // fileName is the name of the image file try { FileUtils.copyFile(screenshot, new File(fileName)); } catch (IOException e) { e.printStackTrace(); } } } To give a concrete example, if your fileName is "screenshotTestClass-testName.png", it will be copied to $WORKSPACE/screenshot-TestClass-testName.png. Step 3: Archiving the screenshot as an artifact In Post-build Actions section enable Archive the artifacts and enter the appropriate glob in the textbox below. Your screenshots will appear in the Build Artifacts in build details page