How the environment is built
Required JAR Package: Selenium-server-standalone-2.53.1.jar
Add the above jar package and JUnit to the build path
1. Writing scripts
At first, I didn't know the specific syntax of webdriver, so I changed the format to Java/webdriver/junit with the Selenium IDE, and then copied the code into eclipse, and made the changes on that basis. The code that is copied directly is the JUnit script.
2. Run the script
You can run the script directly in the code by right-click Run as, JUnit Test. The general default is run by Firefox, or you can download the driver of other browsers instead.
3. Create automatic Screenshots
After confirming that the script can function properly, the general automatic screenshot is necessary to enhance the functionality. But because I just began to contact Webdriver, can only read some active screenshots on the Internet code, do not understand those who use monitoring to achieve the purpose of automatic screenshot of the code, only in the active screenshot of the method to improve some, but the current is enough.
Active screenshot: You can only add a screenshot method to each assertion, which will use a lot of duplicated code.
Screenshot method: Autoscreenshot.java
Import Java.io.File;
Import java.io.IOException;
Import Java.text.SimpleDateFormat;
Import java.util.Date;
Import Org.apache.commons.io.FileUtils;
Import Org.openqa.selenium.OutputType;
Import Org.openqa.selenium.TakesScreenshot;
Import Org.openqa.selenium.WebDriver;
public class Autoscreenshot {public
static int t = 1;
public static String GetDateTime () {
SimpleDateFormat df = new SimpleDateFormat ("Yyyymmdd_hhmmss");
Return Df.format (New Date ());
}
public static void screenshot (Webdriver Dr, String dir) {
File screenshot = ((takesscreenshot) DR). Getscreenshotas ( Outputtype.file);
try {
Fileutils.copyfile (screenshot, New File (Dir+getdatetime () + "_" +t+ ". jpg"));
++t;
} catch (IOException e) {
e.printstacktrace ();}}
}
To implement the screenshot operation:
Autoscreenshot.screenshot (Driver, "e:\\selenium\\file\\");
Automatic screenshot using listener:
Http://www.jianshu.com/p/ddc9a3fcc8d9
Because the above method I did not use success, and so on and then try again.
Improved screenshot method: Using the rewritten Assertequals method to implement
The assertion code obtained from the Selenium IDE is written like this:
try {
assertequals, driver.findelement (By.xpath ("//table[@id = ' xxxx ']/tbody/tr[1]/td[4]")). GetText ());
catch (Error e) {
verificationerrors.append (e.tostring ());
}
Failed throws Exception:
@After public
void TearDown () throws Exception {
driver.quit ();
String verificationerrorstring = verificationerrors.tostring ();
if (! "". Equals (verificationerrorstring)) {
fail (verificationerrorstring);
}
}
If you want to implement the active screenshot, you need to include the implementation code in each assertion's throw exception:
try {
assertequals ("1x", Driver.findelement (By.xpath ("//table[@id = ' xxxx ']/tbody/tr[1]/td[1]")). GetText ());
catch (Error e) {
verificationerrors.append (e.tostring ());
Autoscreenshot.screenshot (Driver, "e:\\selenium\\file\\");
}
This makes the code a lot, and then decides to rewrite a method with the following code:
Import static org.junit.Assert.assertEquals;
Import Org.openqa.selenium.WebDriver;
public class baseclass{
private StringBuffer verificationerrors;
Private Webdriver driver;
Public BaseClass (StringBuffer verificationerrors,webdriver driver) {
this.verificationerrors = verificationerrors;
This.driver = driver;
}
public void Assertequalsrewrite (object A, object B) {
try{
assertequals (b);
} catch (Error e) {
autoscreenshot.screenshot (driver, "e:\\selenium\\file\\screenshot\\");
SYSTEM.OUT.PRINTLN ("Expected Result:" + A + "," + "Actual Result:" + b);
Verificationerrors.append (E.tostring ());}}}
The specific function is actually assertion assertequals, just above it added the assertion failure throws exception and screenshot function.
Using the method, add the following code to the test class:
BaseClass BaseClass = new BaseClass (verificationerrors,driver);
Baseclass.assertequalsrewrite ("1", Driver.findelement (By.xpath ("//table[@id = ' xxxx ']/tbody/tr[1]/td[1]"). GetText ());
Full code:
Autoscreenshot.java
package xxx;
Import Java.io.File;
Import java.io.IOException;
Import Java.text.SimpleDateFormat;
Import java.util.Date;
Import Org.apache.commons.io.FileUtils;
Import Org.openqa.selenium.OutputType;
Import Org.openqa.selenium.TakesScreenshot;
Import Org.openqa.selenium.WebDriver;
public class Autoscreenshot {public
static int t = 1;
public static String GetDateTime () {
SimpleDateFormat df = new SimpleDateFormat ("Yyyymmdd_hhmmss");
Return Df.format (New Date ());
}
public static void screenshot (Webdriver Dr, String dir) {
File screenshot = ((takesscreenshot) DR). Getscreenshotas ( Outputtype.file);
try {
Fileutils.copyfile (screenshot, New File (Dir+getdatetime () + "_" +t+ ". jpg"));
++t;
} catch (IOException e) {
e.printstacktrace ();}}
}
Baseclass.java
package xxx;
Import static org.junit.Assert.assertEquals;
Import Org.openqa.selenium.WebDriver;
public class baseclass{
private StringBuffer verificationerrors;
Private Webdriver driver;
Public BaseClass (StringBuffer verificationerrors,webdriver driver) {
this.verificationerrors = verificationerrors;
This.driver = driver;
}
public void Assertequalsrewrite (object A, object B) {
try{
assertequals (b);
} catch (Error e) {
autoscreenshot.screenshot (driver, "e:\\selenium\\file\\screenshot\\");
SYSTEM.OUT.PRINTLN ("Expected Result:" + A + "," + "Actual Result:" + b);
Verificationerrors.append (E.tostring ());}}}
Testdemo.java (Test Class)
Package xxx;
Import static org.junit.assert.*;
Import Java.util.concurrent.TimeUnit;
Import Org.junit.After;
Import Org.junit.Before;
Import Org.junit.Test;
Import Org.openqa.selenium.By;
Import Org.openqa.selenium.WebDriver;
Import Org.openqa.selenium.firefox.FirefoxDriver;
public class Testdemo {private Webdriver driver;
Private String BaseUrl;
Private StringBuffer verificationerrors = new StringBuffer ();
@Before public void SetUp () throws Exception {driver = new firefoxdriver ();
BASEURL = "http://localhost:8080/";
Driver.manage (). Timeouts (). implicitlywait (Timeunit.seconds);
} @Test public void Testassert () throws exception{Driver.get (BASEURL);
for (int second = 0;; second++) {if (second >=) fail ("timeout");
try {if (Driver.findelement (By.id ("username")). Isdisplayed ()) break;} catch (Exception e) {} thread.sleep (1000);
} driver.findelement (By.id ("username")). Clear (); driver.fiNdelement (By.id ("username")). SendKeys ("Admin");
Driver.findelement (by.id ("password")). Clear ();
Driver.findelement (by.id ("password")). SendKeys ("123456");
for (int second = 0;; second++) {if (second >=) fail ("timeout");
try {if (Driver.findelement (by.id ("Login")). Isdisplayed ()) break;} catch (Exception e) {} thread.sleep (1000);
} driver.findelement (By.id ("Login")). Click ();
Thread.Sleep (1000);
BaseClass BaseClass = new BaseClass (verificationerrors,driver); Baseclass.assertequalsrewrite ("1", Driver.findelement (By.xpath ("//table[@id = ' xxxx ']/tbody/tr[1]/td[1]").
GetText ()); Baseclass.assertequalsrewrite ("Driver.findelement", By.xpath ("//table[@id = ' xxxx ']/tbody/tr[1]/td[4]").
GetText ()); Baseclass.assertequalsrewrite ("1042", Driver.findelement (By.xpath ("//table[@id = ' xxxx ']/tbody/tr[1]/td[5]").
GetText ());
SYSTEM.OUT.PRINTLN ("group 1"); } @After public void TearDown () throws Exception {DrIver.quit ();
String verificationerrorstring = verificationerrors.tostring (); if (! "".
Equals (verificationerrorstring)) {fail (verificationerrorstring);
}
}
}
This screenshot is complete and the image is saved in "e:\\selenium\\file\\screenshot\\" If an assertion error is made
4. Using ant to generate JUnit test reports
Ant is a self-contained tool in Eclipse, so you don't need to install it, using the following method.
1> ensure that each test has been run again
2> Right-click Project-----general--Ant buildfiles---Select the Required project name check box, and others are the default, clicking Next and Finish, and then in the root directory Generate Build.xml File
3> Modifying Build.xml files
The specific code is as follows:
<?xml version= "1.0" encoding= "UTF-8" standalone= "no"?> <!--warning:eclipse auto-generated file.
Any modifications would be overwritten. To include a user specific buildfile here, simply create one in the same directory with the processing InStr Uction <?eclipse.ant.import?> as the first entry and export the BuildFile again. --><project basedir= "." default= "Build" Name= "Regressiontest" > <property environment= "env"/> <PR Operty name= "Eclipse_home" value= "D:/dev/eclipse/eclipse"/> <property name= "Junit.output.dir" value= "JUnit"/&
Gt <property name= "DebugLevel" value= "Source,lines,vars"/> <property name= "target" value= "1.7"/> <prop Erty name= "source" value= "1.7"/> <path id= "JUnit 4.libraryclasspath" > <pathelement location= "${ecl Ipse_home}/plugins/org.junit_4.11.0.v201303080030/junit.jar "/> <pathelement location=" ${ECLIPSE_Home}/plugins/org.hamcrest.core_1.3.0.v201303031735.jar "/> </path> <path id=" Regressiontest.classpath "> <pathelement location=" bin "/> <pathelement location=" E:/selenium/selenium-server-standalone
-2.53.1.jar "/> <path refid=" JUnit 4.libraryclasspath "/> </path> <target name=" Init "> <mkdir dir= "bin"/> <copy includeemptydirs= "false" todir= "Bin" > <fileset dir= "sr C "> <exclude name=" **/*.launch "/> <exclude name=" **/*.java "/> & lt;/fileset> </copy> </target> <target name= "clean" > <delete dir= "Bin"/>
; </target> <target depends= "clean" name= "Cleanall"/> <target depends= "Build-subprojects,build-projec
T "name=" Build "/> <target name=" build-subprojects "/> <target depends=" init "name=" Build-project "> <echo mesSage= "${ant.project.name}: ${ant.file}"/> <javac debug= "true" Debuglevel= "${debuglevel}" destdir= "Bin" inclu Deantruntime= "false" Source= "${source}" target= "${target}" > <src path= "src"/> <classpa Th refid= "Regressiontest.classpath"/> </javac> </target> <target description= "Build all Projects which reference this project. Useful to propagate changes. "Name=" build-refprojects "/> <target description=" copy Eclipse compiler jars to Ant lib directory "name=" Init-eclipse-compiler "> <copy todir=" ${ant.library.dir} "> <fileset di R= "${eclipse_home}/plugins" includes= "Org.eclipse.jdt.core_*.jar"/> </copy> <unzip dest= "${ant . Library.dir} "> <patternset includes=" Jdtcompileradapter.jar "/> <fileset dir=" ${ECLIPS
E_home}/plugins "includes=" Org.eclipse.jdt.core_*.jar "/> </unzip> </target><target description= "Compile project with Eclipse compiler" Name= "Build-eclipse-compiler" > <property name = "Build.compiler" value= "Org.eclipse.jdt.core.JDTCompilerAdapter"/> <antcall target= "Build"/> </ta rget> <target name= "Testdemo" > <mkdir dir= "${junit.output.dir}"/> <junit fork= "yes" printsummary= "Withoutanderr" > <formatter type= "xml"/> <test name= "xxx" todir= "${junit . Output.dir} "/> <classpath refid=" Regressiontest.classpath "/> </junit> <antcall target= "Junitreport"/> </target> <target name= "Junitreport" > <junitreport todir= "${juni T.output.dir} "> <fileset dir=" ${junit.output.dir} "> <include name=" test-*.xml "/>
;
</fileset> <report format= "frames" todir= "${junit.output.dir}"/> </junitreport> </targeT> </project>
The main concern is the following code section, which needs to correspond with its own project name and class name, package name.
Regressiontest, Regressiontest.classpath, Testdemo, xxx
Pay particular attention to the code of <antcall target= "Junitreport"/>, Because the previously generated build.xml file does not have this code, so no matter how I run all only generated JUnit folder and an XML file, and no online said index.html file, later looked at a lot of other people's code to find that they all have this code, added and sure enough to generate a lot of files.
4> Run Build.xml Generate report
Right-click Build.xml-> Run as-Ant Build ...--Select the desired test name in targets (Build [default] is required on the default tick) or in target execution order Run test cases with the sort of test case, and then you will build the JUnit folder under the root directory, and you will see the index.html file in the Web browser, and you'll have a test report.
PS: Originally wanted to implement all the test cases do not close the browser function, but the online has not been found a viable method, some people say this does not conform to the test rules, but I think now every test a case need to close the browser Restart browser is really annoying, Then see if there is any other way to continue with the next test without restarting the browser, in the case of the previous test results.