Java+testng+maven+selenium Web Automation test Script Environment Building

Source: Internet
Author: User
Tags gettext xpath testng

First, Environment construction

1. Installing the Java Environment

A. Installing the JDK

B. Install Eclipse

C. Install Maven

Reference: http://www.cnblogs.com/s1328/p/4620812.html

2. Install the testng plugin under eclipse

In Eclipse click Help->install New software, click Add

Enter Http://beust.com/eclipse at location

Select TestNG version, click Next, follow the prompts to install, restart eclipse after installation

3. Install Firefox plugin

A, Firebug plug-in, help you locate page elements

b, Firepath plugin, you can directly tell you the XPath of the page element

Below we need to create an Eclipse project in eclipse for the Web Automation test we are going to do

You need to follow File-new-project-maven-maven project to create a Maven project

Here, for the sake of simplicity, you can go straight to GitHub and get my project created.

Https://github.com/zhangting85/simpleWebtest

Don't use GitHub's classmates just open this connection and click on the download Zip button to download to the created project source code.

Then, in Eclipse, follow File-import-maven-existing Maven projects to import the source code you just downloaded.

Detailed Engineering Structure:

One of the simplest standard MAVEN projects, where the source code is placed under the Src/main/java directory, the test code is placed in the Src/test/java directory;

MAVEN also created a pom.xml that manages the jar packages that the project relies on for you.

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>simple-webtest</groupId> <artifactId> Simple-webtest</artifactid> <version>0.0.1-SNAPSHOT</version> <packaging>jar</ Packaging> <name>simple-webtest</name> <url>http://maven.apache.org</url> < Properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties > <dependencies> <dependency> <groupId>org.testng</groupId> &LT;ARTIFAC tid>testng</artifactid> <version>6.8.5</version> </dependency> <dependenc Y> <groupId>org.seleniumhq.selenium</groupId> <artifactid>selenium-java</artifactid> <version>2.40.0</version> </dependency> </dependencies> </project>

The upper <version>2.40.0</version> Middle is the version number, if selenium to upgrade from 2.40 to 2.41, we only need to change the version number here. There is no need to go to the official website to download jar packs.

Isn't it convenient?

4. Check if the environment is ready to complete

In the project that was just imported in eclipse, find the Testwebdriverenv.java file under the Simplewebtest.test package.

Right-Run as-testng Test

If the previous steps are installed correctly, you will see selenium open your Firefox browser and jump to the page where my GitHub project is located.

The command line will output Hello World, TestNG.

In addition, TestNG will create a test-output directory in your project directory with the default TESTNG test report.

Good. This is a selenium scripting development environment.

The above test code only uses Firefox, if you want to create a test script for Chrome, IE,

You also need to download the corresponding driver files and put them in your system's environment variable path.

For example, IE's driver file is IEDriverServer.exe. If you need a friend, go to the official website to download it.

Second, write a simple linear script

1. Principle of automatic testing

Automated testing, generally in three steps:

1) Take the expected results;

2) take actual results;

3) Assert: Compare 1) and 2) to determine whether the test passed;

2, simple selenium test script writing, is generally divided into three steps:

1) Positioning an element

2) manipulating an element

3) Assertion

Here to use Baidu homepage Search to do an example:

Package simplewebtest.test; 2 3 Import Java.util.concurrent.TimeUnit; 4 5 Import Org.openqa.selenium.By; 6 Import Org.openqa.selenium.WebDriver; 7 Import Org.openqa.selenium.firefox.FirefoxDriver; 8 Import Org.testng.annotations.Test; 9 public class Testbaiduhome {one @Test13 public void searchsomething () {Webdriver Driver=ne W firefoxdriver ();//Open Firefox firefox16 driver.get ("http://www.baidu.com");//Open the URL17 driv Er.findelement (By.id ("KW1")). SendKeys ("GitHub");//Enter the search keyword "github"; input search Keyword18 driver.findelement (by.id ("SU1")). Click ();///Tap the search button click the Button19 driver.manage (). Timeouts (). implicitlywait (timeunit.seconds);//etc page loading, The report timeout does not load successfully within 10 seconds. Waiting for ten seconds String aresult=driver.findelement (By.xpath (".//*[@id = ' 4 ']/h3/a")) . GetText ();//Take the title of the fourth search result. Get the text of 4th search result21 assert Aresult.contains ("GitHub");//Make assertion Assertion22 DRiver.findelement (By.xpath (".//*[@id = ' 4 ']/h3/a")). Click ();//Open the fourth search result. Open the 4th search result on Baidu23 driver.manage (). Timeouts (). Implicitlywait (Ten, timeunit.seconds);//etc page load, within 10 seconds The report timeout does not load successfully. Waiting for seconds 24 25//Get all windows handle, then switch one by one until you switch to the latest window switch to the new win     Dow26 for (String winHandle:driver.getWindowHandles ()) {Driver.switchto (). window (Winhandle); A String atitle=driver.gettitle (), or a new window Title31 System.out.println ("C Urrent widnow title is: "+atitle);//call out to see the Assert Atitle.contains (" GitHub ");//Assert 33 34}35}

The following lines explain this:

Webdriver driver=new firefoxdriver ();

Reference: http://www.cnblogs.com/sdet/p/3633639.html

Here is the declaration of a Webdriver type object reference, I gave him the name driver;

Then let this driver point to the object of a subclass (Firefoxdriver) of Webdriver;

We know firefoxdriver inherit from Webdriver,iedriver also inherit from Webdriver;

Just as apples inherit from fruit, and oranges inherit from fruit;

This uses the upward transformation of Java to initialize the reference of the parent class with the object of the child class. (Note: Webdriver is actually an interface.) )

What effect will this produce?

When we invoke the method on the driver, we look for the method definition in the Webdriver, and then the JVM goes to his subclass such as Firfoxdriver to find its implementation in the subclass, and then executes it. For example, the Firefoxdriver get method and the Iedriver get method, their specific execution of the code content is obviously not the same. But our script just changes the subclass of the driver reference without changing the method call behind me.

In other words, we use Firefox and IE, in addition to the first sentence of the new object is not the same, the subsequent method calls are the same.

Java automatically chooses the actual code that he should execute based on the object that we created in the above phrase.

This is the polymorphism in Java, one word remembers polymorphism: The parent class reference is initialized with the subclass object, the subclass code is automatically executed when the method is called, and the parent class member variable is called automatically when the member variable is called.

Above, the topic is slightly more, it is hoped that testers do not give up, write a program will not be how difficult, Java Foundation must master.

Driver.get ("http://www.baidu.com");

Call Webdriver's Get method and jump to the established URL;

In general, it is because the webdriver version is too low, the browser version is too high, please change the previous section of the Pom.xml configuration of the Webdriver version number to the latest version.

Driver.findelement (By.id ("KW1")). SendKeys ("GitHub");//Enter the search keyword "github"; input searches Keyworddriver.findelement ( By.id ("SU1")). Click ();//Tap the search button click the

This calls Webdriver's Findelement method to find the page element. Then call the SendKeys method on the found page element Webelement object to click on the typing and click Method.

If you ask me the value of this ID is how to come, then you can go to see firebug this plugin, he will find you every element of the attributes.

If you want to locate the element without an ID, you can also use CLASSNAME,XPATH,CSS, and so on to locate.

Another plugin, Firepath, can help you produce an XPath expression of any element.

methods for locating XPath reference : http://www.cnblogs.com/s1328/p/4931145.html

Driver.manage (). Timeouts (). implicitlywait (Timeunit.seconds);

A very common statement that waits for a page to load. This implicitywait will work for the next findelement call to driver.

Baidu This search results page is very interesting, although we do not feel, but the search results are actually asynchronous display up, so do not wait for him will not find the element.

And then click on the search results to open a window when we use the wait again.

In addition, this method is not valid for all pages, and sometimes we have to wait with some other. And try not to use Thread.Sleep.

String aresult=driver.findelement (By.xpath (".//*[@id = ' 4 ']/h3/a")). GetText ();//Take the title of the fourth search result. Get the text of 4th search Resultassert aresult.contains ("GitHub");//Make Assertions assertion

In these two sentences, we first go to the actual result, that is, the text on the search result element found by an XPath expression

Then, judging whether he meets the expected results, it contains the string "GitHub".

Assert is provided by testng, do not use if else to judge the string. The testng's assert results are reflected in the test report.

Do not throw an exception that represents an assertion failure, and testng will do it for you.

The above two errors are often committed by middle-and low-level developers who write test frameworks.

Since we have used testng, please at least try to use the testng function.



    For (String winHandle:driver.getWindowHandles ()) {                 Driver.switchto (). window (winhandle);                 }  

This code represents a toggle window. Interestingly, he is in the window open, first take out all the windows of the Hanles, and then one by one cut past.

Because the new window must be at the end, no matter how many windows you have, this code will always find the latest window. If you still need to manipulate the old window,

You can save the old window's handle in advance and cut it back later.

One of these simple linear test scripts is written. Basic element positioning, element manipulation, window switching, assertions all have, you can see the official website of the document, learn more ways of the various APIs.

Proficiency in writing linear scripts takes about a month, a faster programming basis, and the content of this article is basically no difficulty. The next article introduces advanced linear scripts, including Frame,actions, close the browser, and run javascript,webdriverwait.

Java+testng+maven+selenium Web Automation test Script Environment Building

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: info-contact@alibabacloud.com 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.