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 org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterClass; import 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(); }
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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 org.openqa.selenium.WebDriver;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.ui.Wait;import org.openqa.selenium.support.ui.WebDriverWait;import org.testng.Assert;import org.testng.annotations.AfterClass;import org.testng.annotations.BeforeClass; public class WebDriverTestBase {
public static FirefoxDriver driver;public static Wait wait;
@Test(description = "Sends an e-mail from Yahoo account")public void sendFromYahoo() {
//new message variablesString to = HOTMAIL_EMAIL;String subject = "Test Sending Email Message From Yahoo";String message = "This is a test e-mail from Yahoo";
//login to yahoodriver.get("http://mail.yahoo.com/");
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 herewait.until(new
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_Windows); // Open second popup jasminedriver.findElement(By.xpath("//*[@id='content']/div[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);
@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.
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-webdriver-tests/" \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-webdriver-tests/" \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 SuiteThe 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:
public class NconaTestSuite{ public static void main( HYPERLINK "http://www.google.com/search?hl=en&q=allinurl%3Astring+java.sun.com&btnI=I%27m%20Feeling%20Lucky" String[] args) { // Objects that are going to be passed to all test classes WebDriver driver = new FirefoxDriver(); Wait<WebDriver>wait = new WebDriverWait(driver, 30);
boolean result; try { // Here we add all the test classes we want to run MiscTestClass mtc1 = new MiscTestClass(); MiscTestClassTwo mtc2 = new MiscTestClassTwo(); MiscTestClassThree mtc3 = new MiscTestClassThree();
// We call the run method (that method runs all // the tests of the class) 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/search?hl=en&q=allinurl%3Aexception+java.sun.com&btnI=I%27m%20Feeling%20Lucky" Exception e) { e.printStackTrace(); result = false; } finally { driver.close(); }
// Run all the methods and return false if any fails return ( miscMethod() && miscMethod2() ); }
private static boolean miscMethod() { // Put your tests code here
return result }
private static boolean miscMethod2() { // 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:
<target name="run-example" description="run command-line example"> <!---- This is the line I modified. Classname is now com.ncona.${example} ----> <java classname="com.ncona.${example}" failonerror="true" classpathref="testautomation.classpath"/> </target></project>
Run the suiteFirst 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
//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 WebDriverMarch 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:
Selenium Grid with WebDriverI had earlier covered in my blog on how to execute your RC cases in selenium grid. But with the commencement of Selenium-2/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-22. Java 1.6 and above3. TestNg jar . You can download it from the link: HYPERLINK "http://testng.org/doc/download.html" TestNG4. Eclipse with TestNG plugin installed(optional)5. ChromeDriver. Can be downloaded from: HYPERLINK "http://code.google.com/p/chromium/downloads/list" ChromeDriver
The Test CodeFollowing is an example of test-class that have a test case to search google for "testing" and verifying after clicking it on a link.
@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 configurationFor 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 serverNow 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.
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/Grid2Example 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 Data-driven 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-testing-using-junit-and.html" ?1234567
import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebDriverBackedSelenium;import org.openqa.selenium.firefox.FirefoxDriver;import org.testng.Assert;import org.testng.annotations.AfterMethod;import org.testng.annotations.BeforeMethod;import org.testng.annotations.DataProvider;import org.testng.annotations.Test; public class TestNGGoogleBase { public Selenium selenium; WebDriver driver; @DataProvider(name="parameter") public static Object[][] data() { return new Object[][]{{"testing"},{"Software testing"}}; }
454647484950515253545556
@BeforeMethod public void setUp() throws Exception { driver= new FirefoxDriver(); selenium = new WebDriverBackedSelenium(driver, " HYPERLINK "http://www.google.com/" http://www.google.com"); selenium.open(" HYPERLINK "http://www.google.com/" http://www.google.com"); } @Test(dataProvider="parameter") public void testSearch(String testData) throws Exception { selenium.open("/"); selenium.type("id=lst-ib", testData); 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) {} Thread.sleep(1000);
} selenium.click("link=Software 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(); } }<span class="Apple-style-span" style="font-family: Verdana, sans-serif;"></span>
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 test-method, but the same is not possible in Junit.
Example Ten:
HYPERLINK "http://blog.varunin.com/2010/05/generating-selenium-reports-using.html" Generating selenium reports using TestNG-xslt through AntTestNG-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-xslt2. 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\saxon-8.7.jar)to your project lib folder.4. Modify your build.xml of ant and add the following target to it.
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_CLASSYou need to provide the testng-xslt stylesheet the TestNG results xml(testng-results.xml) , the path to the style sheet testng-results.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 "testng-xslt-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?
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();
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.
@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 "screenshot-TestClass-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