If you are using Internet Explorer 8 or higher you can press F12 to
open the developer tools. If you are using Firefox you need to install Firebug then F12 will open Firebug. If you are using Chrome then CTRL- SHIFT-I will open the developer tools. Beyond that, the only tool I use is my brain and the W3 standards. Reading the W3 standards (or any standards documentation, ISO, ANSI, IEEE, etc.) can be difficult at first. Especially if you have been learning from books like "Web Design in 21 Days" or "Software Testing for Dummies." However, the more you read and understand standards documentation, the easier it gets to read other standards documents. If generating XPath was easy enough for a piece of software then why would they pay you to do the work? There are probably a dozen XPath locators for any given element on a page. Some will work once and need to be revised on the next release of the application. Some will work within the design pattern of the application and might never need updating. There is no way for a piece of software to spot the design pattern and know which locator will work best. This is what they pay you to do. Excessively long XPath is brittle and will need a great deal of revising from release to release. Extremely short XPath will sometimes find the wrong element between releases. This leads to a test which fails unpredictably and can be difficult to debug. Not something you want in an automation suite. Finding the right balance is your job. The first time you select a locator it might need revising for the next release. You need to look at why you selected the first locator when selecting the revised locator. The second locator should work for the first release and the second release. When the locator fails, you need to select a new locator which would have worked on the first release and all subsequent releases, including the next release. After a while you should start to see the pattern. The pattern is usually derived from some design pattern the application is being developed with. Learn about Design Patterns, it will be extremely helpful in generating good test automation. If the developers change the tools, libraries, design patterns, etc. you should expect the locators to fail. At this point, selecting a locator which works with the next release but does not work with the previous release makes sense. Major change in development usually implies major change in test automation. It would be difficult for a tool to realize when it needs to abandon old locators. Essentially, automation is all about finding elements (locators), performing actions on them, confirming the expected results (usually involves more locators). Two thirds of the work is about the locators. Learning XPath, CSS and DOM will make your job that much easier. XPath 1.0: http://www.w3.org/TR/xpath/ XPath 2.0: http://www.w3.org/TR/xpath20/ XPath functions: http://www.w3.org/TR/xpath-functions/ CSS 1.0: http://www.w3.org/TR/2008/REC-CSS1-20080411/ CSS 2.0: http://www.w3.org/TR/CSS2/ CSS 3.0: http://www.w3.org/TR/selectors/ DOM: http://www.w3.org/TR/DOM-Level-2-HTML/html.html When possible, use CSS selectors as they are faster. Some things are easier to locate using XPath and XQuery (XPath functions). It is better to have a test run slow and be easy to maintain. So if CSS selectors are complex and unintuitive you might want to use XPath functions instead.
5 Comments
Selenium 2.0 and WebDriverNOTE:
We’re currently working on documenting these sections. We believe the information here is accurate, however be aware we are also still working on this chapter. Additional information will be provided as we go which should make this chapter more solid. In addition, we will be proofreading and reviewing it. Selenium 2.0 FeaturesSelenium 2.0 has many new exciting features and improvements over Selenium 1. These new features are introduced release in the release announcement in the Official Selenium Blog. The primary new feature is the integration of the WebDriver API. This addresses a number of limitations along with providing an alternative, and simpler, programming interface. The goal is to develop an object-oriented API that provides additional support for a larger number of browsers along with improved support for modern advanced web-app testing problems. NOTE: We will add a description of SEL 2.0 new features–for now we refer readers to the release announcement. The Selenium Server – When to Use ItYou may, or may not, need the Selenium Server, depending on how you intend to use Selenium. If you will be strictly using the WebDriver API you do not need the Selenium Server. The Selenium Server provides Selenium-RC functionality, which is primarily used for Selenium 1.0 backwards compatability. Since WebDriver uses completely different technology to interact with the browsers, the Selenium Server is not needed. Selenium-WebDriver makes direct calls to the browser using each browser’s native support for automation. Selenium-RC however requires the Selenium- Server to inject javascript into the browser and to then translate messages from your test program’s language-specific Selenium client library into commands that invoke the javascript commands which in turn, automate the AUT from within the browser. In short, if you’re using Selenium-WebDriver, you don’t need the Selenium-Server. Another reason for using the Selenium-Server is if you are using Selenium-Grid for distributed exectution of your tests. Finally, if you are using Selenium-backed Web-Driver (the WebDriver API but with back-end Selenium technology) you will also need the Selenium Server. These topics are described in more detail later in this chapter. Setting Up a Selenium-WebDriver ProjectTo install Selenium means to set up a project in a development so you can write a program using Selenium. How you do this depends on your programming language and your development environment. Getting Started With Selenium-WebDriver WebDriver is a tool for automating testing web applications, and in particular to verify that they work as expected. It aims to provide a friendly API that’s easy to explore and understand, easier to use than the Selenium-RC (1.0) API, which will help make your tests easier to read and maintain. It’s not tied to any particular test framework, so it can be used equally well in a unit testing or from a plain old “main” method. This section introduces WebDriver’s API and helps get you started becoming familiar with it. Start by setting up a WebDriver project if you haven’t already. This was described in the previous section, Setting Up a Selenium-WebDriver Project. Once your project is set up, you can see that WebDriver acts just as any normal library: it is entirely self-contained, and you usually don’t need to remember to start any additional processes or run any installers before using it, as opposed to the proxy server with Selenium-RC. You’re now ready to write some code. An easy way to get started is this example, which searches for the term “Cheese” on Google and then outputs the result page’s title to the console. how to learning script by Java: plz notice why we used which lines. That make you understand how to learn scripting package org.openqa.selenium.example; // importing selenium in code space import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class Selenium2Example { public static void main(String[] args) { // Create a new instance of the Firefox driver // Notice that the remainder of the code relies on the interface, // not the implementation. WebDriver driver = new FirefoxDriver(); // And now use this to visit Google driver.get("http://www.google.com"); // Alternatively the same thing can be done like this // driver.navigate().to("http://www.google.com"); // Find the text input element by its name WebElement element = driver.findElement(By.name("q")); // Enter something to search for element.sendKeys("Cheese!"); // Now submit the form. WebDriver will find the form for us from the element element.submit(); // Check the title of the page System.out.println("Page title is: " + driver.getTitle()); // Google's search is rendered dynamically with JavaScript. // Wait for the page to load, timeout after 10 seconds (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().startsWith("cheese!"); } }); // Should see: "cheese! - Google Search" System.out.println("Page title is: " + driver.getTitle()); //Close the browser driver.quit(); }} Moving Between Windows and Frames Some web applications have any frames or multiple windows. WebDriver supports moving between named windows using the “switchTo” method: driver.switchTo().window("windowName");All calls to driver will now be interpreted as being directed to the particular window. But how do you know the window’s name? Take a look at the javascript or link that opened it: <a href="somewhere.html" target="windowName">Click here to open a new window</a> Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:for (String handle : driver.getWindowHandles()) { driver.switchTo().window(handle); } You can also swing from frame to frame (or into iframes):driver.switchTo().frame("frameName");It’s possible to access subframes by separating the path with a dot, and you can specify the frame by its index too. That is: driver.switchTo().frame("frameName.0.child");would go to the frame named “child” of the first subframe of the frame called “frameName”.All frames are evaluated as if from *top*. User Input - Filling In FormsWe’ve already seen how to enter text into a textarea or text field, but what about the other elements? You can “toggle” the state of checkboxes, and you can use “click” to set something like an OPTION tag selected. Dealing with SELECT tags isn’t too bad: WebElement select = driver.findElement(By.xpath("//select")); List<WebElement> allOptions = select.findElements(By.tagName("option")); for (WebElement option : allOptions) { System.out.println(String.format("Value is: %s", option.getAttribute("value"))); option.click(); } This will find the first “SELECT” element on the page, and cycle through each of its OPTIONs in turn, printing out their values, and selecting each in turn. As you will notice, this isn’t the most efficient way of dealing with SELECT elements. WebDriver’s support classes include one called “Select”, which provides useful methods for interacting with these. Select select = new Select(driver.findElement(By.xpath("//select"))); select.deselectAll(); select.selectByVisibleText("Edam"); This will deselect all OPTIONs from the first SELECT on the page, and then select the OPTION with the displayed text of “Edam”. Once you’ve finished filling out the form, you probably want to submit it. One way to do this would be to find the “submit” button and click it: driver.findElement(By.id("submit")).click(); // Assume the button has the ID "submit" :)Alternatively, WebDriver has the convenience method “submit” on every element. If you call this on an element within a form, WebDriver will walk up the DOM until it finds the enclosing form and then calls submit on that. If the element isn’t in a form, then the NoSuchElementException will be thrown: Navigating
The first thing you'll want to do with WebDriver is navigate to a page. The normal way to do this is by calling "get": driver.get("http://www.google.com"); WebDriver will wait until the page has fully loaded (that is, the "onload" event has fired) before returning control to your test or script. Interacting With the Page Just being able to go to places isn't terribly useful. What we'd really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. First of all, we need to find one. WebDriver offers a number of ways of finding elements. For example, given an element defined as: <input name="passwd" id="passwd-id" /> we could use any of: WebElement element; element = driver.findElement(By.id("passwd-id")); element = driver.findElement(By.name("passwd")); element = driver.findElement(By.xpath("//input[@id='passwd-id']")); Filling In FormsWe've already seen how to enter text into a textarea or text field, but what about the other elements? You can "toggle" the state of checkboxes, and you can use "setSelected" to set something like an OPTION tag selected. Dealing with SELECT tags isn't too bad: WebElement select = driver.findElement(By.xpath("//select")); List<WebElement> allOptions = select.findElements(By.tagName("option")); for (WebElement option : allOptions) { System.out.println(String.format("Value is: %s", option.getValue())); option.setSelected(); } This will find the first "SELECT" element on the page, and cycle through each of it's OPTIONs in turn, printing out their values, and selecting each in turn. As you can see, this isn't the most efficient way of dealing with SELECT elements. WebDriver's support classes come with one called "Select", which provides useful methods for interacting with these. Once you've finished filling out the form, you probably want to submit it. One way to do this would be to find the "submit" button and click it: driver.findElement(By.id("submit")).click(); // Assume the button has the ID "submit" :) Alternatively, WebDriver has the convenience method "submit" on every element. If you call this on an element within a form, WebDriver will walk up the DOM until it finds the enclosing form and then calls submit on that. If the element isn't in a form, then the "NoSuchElementException" will be thrown: element.submit() Getting Visual Information And Drag And DropSometimes you want to extract some visual information out of an element, perhaps to see if it's visible or where it is on screen. You can find out this information by casting the element to a RenderedWebElement: WebElement plain = driver.findElement(By.name("q")); RenderedWebElement element = (RenderedWebElement) plain; Not all drivers render their content to the screen (such as the HtmlUnitDriver), so it's not safe to assume that the cast will work, but if it does you can gather additional information such as the size and location of the element. In addition, you can use drag and drop, either moving an element by a certain amount, or on to another element: RenderedWebElement element = (RenderedWebElement) driver.findElement(By.name("source")); RenderedWebElement target = (RenderedWebElement) driver.findElement(By.name("target")); element.dragAndDropOn(target); Moving Between Windows and FramesIt's rare for a modern web application not to have any frames or to be constrained to a single window. WebDriver supports moving between named windows using the "switchTo" method: driver.switchTo().window("windowName"); All calls to driver will now be interpreted as being directed to the particular window. But how do you know the window's name? Take a look at the javascript or link that opened it: <a href="somewhere.html" target="windowName">Click here to open a new window</a> Alternatively, you can pass a "window handle" to the "switchTo().window()" method. Knowing this, it's possible to iterate over every open window like so: for (String handle : driver.getWindowHandles()) { driver.switchTo().window(handle); } You can also swing from frame to frame (or into iframes): driver.switchTo().frame("frameName"); It's possible to access subframes by chaining switchTo() calls, and you can specify the frame by its index too. That is: driver.switchTo().frame("frameName") .switchTo().frame(0) .switchTo().frame("child"); would go to the frame named "child" of the first subframe of the frame called "frameName". All frames are evaluated as if from currently switched to frame. To get back to the top level, call: driver.switchTo().defaultContent(); There are several steps required to prepare the android device or emulator, the environment and the computer. These include: · Installing android-server.apk (the actual filename may differ e.g. if you use a prebuilt version it will include the release name). If you want to use an emulator, we currently recommend using one with Android 2.2 installed. The server doesn’t support earlier versions any more (it used to but limitations with the platform e.g. lack of support for XPath meant the project team have chosen to target a minimum of 2.2). There’s currently an issue with the Java-to-JavaScript bridge in version 2.3 of the emulator, so again we don’t recommend using it currently.) · Configuring port forwarding so your tests can communicate with the device or running instance of the emulator. · Starting the WebDriver Server on the Android emulator (or on a device). Configuring your eclipse project You will need to include the various jar files from the selenium project in order for your tests to use ‘RemoteWebdriver’. The AndroidDriver implements the RemoteWebdriver protocol. You can download a zip file from the selenium project site http://code.google.com/p/selenium/downloads/list e.g. selenium-java-2.0b1.zip currently. This file needs to be unzipped, which will unpack to 2 selenium jar files (the code and the javadoc documentation) and a series of 27 other jar files. All these files need to be added to the build path in your eclipse project. I suggest copying all the files into a common libs folder for your project. First, let's create an Android Virtual Device (AVD): $cd ~/android_sdk/tools/ $./android create avd -n my_android -t 12 -c 100M -n: specifies the name of the AVD. -t: specifies the platform target. For an exhaustive list of targets, run: ./android list targets Make sure the target level you selected corresponds to a supported SDK platform. -c: specifies the SD card storage space. When prompted "Do you wish to create a custom hardware profile [no]" enter "no". Now, start the emulator. This can take a while, but take a look at the FAQ below for tips on how to improve performance of the emulator. $./emulator -avd my_android & Install the WebDriver APKEvery device or emulator has a serial ID. Run this command to get the serial ID of the device or emulator you want to use: $~/android_sdk/platform-tools/adb devices Download the Android server from selenium download page To install the application do: $./adb -s <serialId> -e install -r android-server.apk Make sure you are allowing installation of application not coming from Android Market. Go to Settings -> Applications, and check "Unknown Sources". Start the Android WebDriver application through the UI of the device or by running this command: $./adb -s <serialId> shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity You can start the application in debug mode, which has more verbose logs by doing: $./adb -s <serialId> shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity -e debug true Sample Code: just put that inside a class and check the magic, Run the Testsimport junit.framework.TestCase; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.android.AndroidDriver; public class OneTest extends TestCase { public void testGoogle() throws Exception { WebDriver driver = new AndroidDriver(); // And now use this to visit Google driver.get("http://www.google.com"); // Find the text input element by its name WebElement element = driver.findElement(By.name("q")); // Enter something to search for element.sendKeys("Cheese!"); // Now submit the form. WebDriver will find the form for us from the element element.submit(); // Check the title of the page System.out.println("Page title is: " + driver.getTitle()); driver.quit(); } }
still confused ??? haha. Really no problem. Check my video tutorial on android webdriver. You will have your all questions answer. what is webdriver ? what is this doing now ? many questions running your mind. right ?
For example, Selenium, a popular and well established testing framework is a wonderful tool that provides a handy unified interface that works with a large number of browsers, and allows you to write your tests in almost every language you can imagine (from Java or C# through PHP to Erlang!). It was one of the first Open Source projects to bring browser-based testing to the masses, and because it's written in JavaScript it's possible to quickly add support for new browsers thatmight be released Like every large project, it's not perfect. Selenium is written in JavaScript which causes a significant weakness: browsers impose a pretty strict security model on any JavaScript that they execute in order to protect a user from malicious scripts. Examples of where this security model makes testing harder are when trying to upload a file (IE prevents JavaScript from changing the value of an INPUT file element) and when trying to navigate between domains (because of the single host origin policy problem). Additionally, being a mature product, the API for Selenium RC has grown over time, and as it has done so it has become harder to understand how best to use it. For example, it's not immediately obvious whether you should be using "type" instead of "typeKeys" to enter text into a form control. Although it's a question of aesthetics, some find the large API intimidating and difficult to navigate. WebDriver takes a different approach to solve the same problem as Selenium. Rather than being a JavaScript application running within the browser, it uses whichever mechanism is most appropriate to control the browser. For Firefox, this means that WebDriver is implemented as an extension. For IE, WebDriver makes use of IE's Automation controls. By changing the mechanism used to control the browser, we can circumvent the restrictions placed on the browser by the JavaScript security model. In those cases where automation through the browser isn't enough, WebDriver can make use of facilities offered by the Operating System. For example, on Windows we simulate typing at the OS level, which means we are more closely modeling how the user interacts with the browser, and that we can type into "file" input elements. With the benefit of hindsight, we have developed a cleaner, Object-based API for WebDriver, rather than follow Selenium's dictionary-based approach. A typical example using WebDriver in Java looks like this: // Create an instance of WebDriver backed by Firefox WebDriver driver = new FirefoxDriver(); // Now go to the Google home page driver.get("http://www.google.com"); // Find the search box, and (ummm...) search for something WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("selenium"); searchBox.submit(); // And now display the title of the page System.out.println("Title: " + driver.getTitle()); Looking at the two frameworks side-by-side, we found that the weaknesses of one are addressed by the strengths of the other. For example, whilst WebDriver's approach to supporting browsers requires a lot of work from the framework developers, Selenium can easily be extended. Conversely, Selenium always requires a real browser, yet WebDriver can make use of an implementation based on HtmlUnit which provides lightweight, super-fast browser emulation. Selenium has good support for many of the common situations you might want to test, but WebDriver's ability to step outside the JavaScript sandbox opens up some interesting possibilities. These complementary capabilities explain why the two projects are merging: Selenium 2.0 will offer WebDriver's API alongside the traditional Selenium API, and we shall be merging the two implementations to offer a capable, flexible testing framework. One of the benefits of this approach is that there will be an implementation of WebDriver's cleaner APIs backed by the existing Selenium implementation. Although this won't solve the underlying limitations of Selenium's current JavaScript-based approach, it does mean that it becomes easier to test against a broader range of browsers. And the reverse is true; we'll also be emulating the existing Selenium APIs with WebDriver too. This means that teams can make the move to WebDriver's API (and Selenium 2) in a managed and considered way. If you'd like to give WebDriver a try, it's as easy as downloading the zip files, unpacking them and putting the JARs on your CLASSPATH. For the Pythonistas out there, there's also a version of WebDriver for you, and a C# version is waiting in the wings. The project is hosted athttp://webdriver.googlecode.com, and, like any project on Google Code, is Open Source (we're using the Apache 2 license) If you need help getting started, the project's wiki contains useful guides, and the WebDriver group is friendly and helpful (something which makes me feel very happy). So that's WebDriver: a clean, fast framework for automated testing of webapps. We hope you like it as much as we do! |
AuthorI am Masud Parvez. Working as IT Senior Project Manager for RMIT University. Previously I built and run a distributed Test Center. My success was to turn that in to one of the most successful business units of the company. Categories
All
|