Reprint of Web application Automation test based on selenium Webdriver

Source: Internet
Author: User
Tags tagname xpath selenium hq selenium grid

Reprint Original Address:

For WEB applications, software testers need a lot of manual action to verify certain features in their daily testing work. During the development process, developers need to access their applications and verify that their functionality is functioning properly, repeatedly debugging duplicate validations. System maintainers also need frequent access to their applications to ensure proper operation of the system. These operations, as described above, take a lot of time and effort, and the ability to introduce automated tests instead of manual duplication will greatly improve team productivity. In this article, we'll show you how to use Selenium 2.0, or Selenium Webdriver, to automate the testing of artifacts.

Automated testing of WEB applications

Today, most applications are written as WEB-based applications and are presented to and interacted with by a browser. Different companies and organizations need to test the effectiveness of these applications. In an era of highly interactive and responsive software processes, many organizations tend to use agile development theory, and automated testing is a must. The so-called automated testing is the implementation of automated testing tools or a programming language to write programs, control the various modules in the software under test, simulate manual test steps, complete the test. Test automation has many advantages, such as frequent regression testing, rapid feedback to developers, virtually unlimited execution of repetitive test cases, support for agile and extreme development methodologies, customized bug reports, and the pitfalls of manual manual testing that may be missed. There are also many commercial and open source software that can assist in the development of test automation. Selenium should be the most widely used open source solution.

Selenium Overview

Selenium is a tool for WEB application testing, and the Selenium test runs directly in the browser, just like a real user does in a manual operation. Supported browsers include IE, Chrome, and Firefox. The main features of this tool include: test and browser compatibility-test your application to see if it works well on different browsers and operating systems, test system functions-Create regression tests to verify software functionality and user needs, support automatic recording actions, and automatically generate. NET, Perl, Python , and test scripts in different languages such as Ruby and Java. Selenium is an acceptance testing tool ThoughtWorks specifically written for WEB applications.

The difference between Selenium 2.0 and previous versions

The main new feature of Selenium 2.0 (aka Selenium Webdriver) is the integration of Webdriver. Webdriver was once a competitor of the Selenium 1 (aka Selenium RC). Selenium RC runs JavaScript applications in the browser, and Webdriver directly controls the browser via native browser support or browser extensions.

As you can see from the brief history of the Selenium project, developers of both Selenium and Webdriver believe that the two tools have advantages and that merging will create a more powerful WEB testing framework. Selenium 1 is a popular and well-developed test framework that supports many browsers (because of their JavaScript implementations), allowing users to use many programming languages (from java/c# to PHP, Erlang ...). , while webdriver compensates for the shortcomings of the Selenium 1, jumping out of the JavaScript sandbox, providing a fast, lightweight browser emulator. The reasons for merging are as follows:

    • Webdriver solves the shortcomings of Selenium (for example, bypassing the JS sandbox);
    • Selenium solves problems with webdriver (e.g. support for a wide range of browsers);
    • Selenium's major contributors feel that merging projects is the best way to provide the best framework for users.

Selenium 2.0 also includes Selenium Server, which supports distributed testing through the Selenium Grid. The new Selenium Grid supports testing with the original Selenium RC API and Webdriver API. Selenium IDE 1.1.0 will also support Webdriver APIs, including exporting test cases generated by recordings to a variety of programming languages supported by Webdriver (Ruby, Python, C #, and Java).

Webdriver, developed for individual browsers, replaces JavaScript embedded in the WEB application under test in Selenium RC, and tight integration with the browser can support the creation of more advanced tests and avoid the limitations of the JavaScript security model. In addition to support from the browser vendor, Webdriver also simulates user input using an operating system-level call. Webdriver supports Firefox (firefoxdriver), IE (Internetexplorerdriver), Opera (Operadriver), and Chrome (Chromedriver). It also supports mobile app testing for Android (Androiddriver) and IPhone (Iphonedriver). In addition, there is a htmlunit-based no-interface implementation, or Htmlunitdriver. The Webdriver API can be accessed through Python, Ruby, Java, and C #, enabling developers to create tests using their preferred programming language.

Selenium installation configuration Selenium IDE installation

The Selenium IDE is a Firefox plug-in, an integrated development tool for developing test cases that is easy to use, has the ability to efficiently develop test cases, and can be translated into the appropriate language scripts.

First, use FireFox to access the Selenium HQ download page to download the Selenium IDE:

Figure 1. Selenium IDE download page

Firefox may pop up a hint for a non-trusted plugin, so you'll need to click the "Allow" button to continue the installation. When the download is complete, the following page pops up:

Figure 2. Installing the Selenium IDE

Click the Install button, you will be prompted to restart the browser after installation, complete the operation, the Selenium IDE is installed complete. As shown in the following:

Figure 3. Selenium IDE

Selenium Development environment

First, download the various class packs that you might need to run the Selenium webdriver in the download page above:

    • Selenium Server 2.25
    • Selenium Client Drivers–java
    • Selenium Internet Explorer Driver server–needed when using IE mode
    • Selenium Chrome Driver

The integrated development environment of this article chooses the Eclipse Java EE IDE Juno, as follows:

Figure 4. Eclipse Development Environment Configuration

You need to add the Junit 4 library, Selenium Java driver (selenium-java-2.25.0.jar), Selenium Server (Selenium-server-2.25.0.jar), the rest The jar package is a dependent class of Selenium Java driver, located in the Lib folder in the Selenium Java Driver zip package.

At this point, the WEB application's automated test development environment is configured.

Selenium Webdriver Common operation

Selenium Webdriver is capable of simulating daily browser operations, the most common of which are as follows:

    1. Visit page
    2. Interacting with pages
    3. Fill out the form
    4. Submit Page Content
    5. Check if page elements are on the page
    6. Move between a window and a Frame
    7. Popup dialog box
    8. Page navigation

The following is a complete example of a specific application of the common operations shown above, respectively. The code snippet is as follows:

Listing 1. Webdriver Common operations
 1.public void SetUp () throws Exception {2.  Driver = new Htmlunitdriver ();  3. Driver = new Firefoxdriver ();  4. BaseUrl = "";  5. Driver.manage (). Timeouts (). implicitlywait (Timeunit.seconds);  6.} 7.  [Email protected]    9.public void Testdemo () throws Exception {10.  Driver.get (BaseUrl + "/");  Driver.findelement ( ("kw")). Clear ();  Driver.findelement (" (" kw ")). SendKeys (" Baidu Translator ");  Driver.findelement ( ("su")). Click ();    14.15.  webelement element;  element = Driver.findelement ( ("Op_tran_text"));  //element = Driver.findelement (By.xpath ("//textarea[@id = ' op_tran_text ']");  Element.clear ();  Element.sendkeys ("Automated testing");    20.21.  Webelement select = Driver.findelement (By.xpath ("//select"));  list<webelement> alloptions = select.findelements (by.tagname ("option"));        . for (Webelement option:alloptions) {24. System.out.println (StrinG.format ("Value is:%s", Option.getattribute ("value"));            if (Option.gettext (). Equals ("Zh2en")) 26. ();  27.} 28.  Driver.findelement (By.xpath ("//a[@class = ' op_tran_btn op_log_btn ']"). Click ();  31.driver.switchto (). Window ("Baidu online translator"); 32.}

The list 第2-3 row defines the type of webdriver used, and this section takes Htmlfirefoxdriver as an example:

Webdriver Driver = new Htmlfirefoxdriver ();

For other types of driver, the operation is the same, and the difference between different driver is the type of browser to emulate.

Page navigation

As shown in line 10th of the list:

Driver.get (BaseUrl + "/");

After the page is fully loaded, control is returned to the test script.

Note: When there are many Ajax calls to the page, the interface cannot confirm that the page is fully loaded, which requires the use of "waits".

Interacting with pages

As shown in Listing 第11-12, line 15-19.

For example:

<input type= "text" name= "passwd" id= "Passwd-id"/>  webelement element;  element = Driver.findelement ( ("Passwd-id"));  element = Driver.findelement ( ("passwd"));  element = Driver.findelement (By.xpath ("//input[@id = ' Passwd-id ')");  The XPATH returns the first match to the element, if not matched to, throws Nosuchelementexception  Element.sendkeys ("some text");  Element.sendkeys ("and some", keys.arrow_down); Press the DOWN arrow; Any page element can call SendKeys,                                   //For example, you can test some shortcut keys, each time the keyboard input is appended to the text string, element.clear ();//Clear Text field contents
Fill out the form

This is shown in the listing 21-27 line.

    • Working with SELECT labels
      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 ();  }
    • Working with SELECT tags using the Select class
      Select select = New Select (Driver.findelement (By.xpath ("//select"));  Select.deselectall ();  Select.selectbyvisibletext ("Edam");

As shown in lines 13th and 29 of the list.

Driver.findelement ( ("submit")). Click ();  Element.submit ();//requires element to be in the form, otherwise throws Nosuchelementexception
Checks if the element is on the page

Checking whether an element is one of the most common operations on a page is as follows:

Webelement plain = driver.findelement ( ("Q"));  renderedwebelement element = (renderedwebelement) element;//such as Htmlunit Driver will not be able to display the content

Drag the element:

renderedwebelement element = (renderedwebelement) driver.findelement (                                              ("source")); Renderedwebelement target = (renderedwebelement) driver.findelement (                                              ("target")); Element.draganddropon ( Target);
Move between a window and a frame

As shown in line 31st of the list

    • Move between named Windows
      Driver.switchto (). Window ("Windowname"); You can get the window name by JS or by opening a link to the window
    • Toggle through window Handles
      For (String handle:driver.getWindowHandles ()) {  Driver.switchto (). window (handle);  }
    • Switch between frame or switch to IFRAME
      Driver.switchto (). FRAME ("FrameName");  Access Subframe:driver.switchTo (). FRAME ("Framename.0.child") by index;//framename's first subframe                                                 //stuffs child's frame
Popup dialog box

After the window pops up, you can access the popup window using the following statement:

Alert alert = Driver.switchto (). alert ();

After you get to the alert window, you can do a variety of things.

Page navigation

The navigate (). to () and get () functions are exactly the same.

Driver.navigate (). to ("");

Browser forward and backward:

Driver.navigate (). Forward ();  Driver.navigate (). back ();

Note that these two methods depend on the implementation of the browser, and some calls may fail.

Combine the Selenium IDE to demonstrate the construction of automated tests with examples

This section will demonstrate the construction of automated tests with practical examples.

Selenium IDE usage and scripting transformations

Open the FireFox browser, as shown in 3, to open the Selenium IDE window:

Figure 5. Selenium IDE window

The following starts recording the first browser-based automation script:

    1. Click the File menu, pop-up drop-down list, select New test Case, when the left Central Test Cases window will be added a Untitle 2 of the tests, right click ' Property ', in the pop-up window renamed to "Testdemo"
    2. Click the upper right of the IDE record button (red dot) to start the manual recording, in FireFox Open a new tab page, enter the test URL, in the search box enter the content to query "Selenium", click "Baidu" button;
    3. In the results page, the first result is Selenium's official website, click the link to enter;
    4. After entering the official website of Selenium, switch to the Selenium IDE window, click the Record button (red dot) to end this manual recording, the Selenium IDE window as shown in 6;
    5. Click on the File menu, select "Save Test Case", fill in the filename "Testdemo", the manual recording script will be saved as a local HTML format file, this file can be imported in other Selenium IDE use;

With the above recorded script, you can play back in Selenium, select the Testdemo script, click on the "Play Current test Case" button in the upper part (the second green triangle button), at which time the browser will be executed automatically in the order of recording. Thus, Selenium IDE in the WEB application test, can replace a person's manual operation.

Figure 6. Script recording

The part of the red box is the Selenium record, where you can add, delete, and change commands manually.

With a manually recorded script, you can convert the program script into multiple languages:

    1. In the Selenium IDE, select a test case, click the File menu, and select "Export Test cases as"-"Java/junit 4/webdriver" in the drop-down list;
    2. In the pop-up Save window, enter the class name Testdemo, save; file generation. Some of the generated Java Automation test scripts may not be executed successfully and require a slight manual adjustment.
Writing the first Selenium Automation test script

Open the previously configured ECLIPSE development environment, create a new Java project, import the converted file into the project, and remove the redundant "Organize import (Ctrl + Shift + O)". 7 is shown below:

Figure 7. Code in an integrated development environment

The Code line 21st is visible, automatically exported code by default in FireFox browser. To execute this code, Selenium will automatically trigger the opening of the FireFox browser, open a new page, enter the Baidu homepage, in the search box automatically enter the "Selenium" keyword, automatically click on the "Baidu" button, go to the Search results page, locate the first results, and then click Enter Selenium official website, automatically close the browser, at this time the Eclipse development environment, the JUNIT results page is shown, 8:

Figure 8. Automated Run Results

Different versions of Webdriver for cross-browser testing

The key to implementing cross-browser testing is which webdriver to choose from.

For IE and Chrome browser

In the case of IE browser, update the code shown in Figure 7 21st Behavior Driver = new Internetexplorerdriver ();

After running the updated Automation script, selenium automatically launches the IE browser for automated testing. 9 is shown below:

Figure 9. Automated test for IE browser

For analog browsers

Selenium provides a Java implementation of the virtual browser, the use of this driver, the program will simulate the behavior of the browser test, the test process and no actual browser is called.

Update Driver = new Htmlunitdriver (); Run the script, and all browser behavior runs in the background simulation.


To sum up, this paper, from the basic concept of Selenium Webdriver, elaborated its differences with the previous version, and the actual case, demonstrated the Selenium implementation of WEB application Automation testing process. Users follow the steps and methods described in this article to build the first automated test case. With the deepening of learning, it is believed that the application of automation test based on Selenium Webdriver to the actual project will greatly improve the working efficiency.

Reprint of Web application Automation test based on selenium Webdriver

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.