当前位置:文档之家› HttpUnit

HttpUnit

HttpUnit
HttpUnit

HttpUnit简介

主页:

https://www.doczj.com/doc/cd79241.html,/

HttpUnit是SourceForge下面的一个开源项目,它是基于JUnit的一个测试框架,主要关注于测试Web应用,解决使用JUnit框架无法对远程Web内容进行测试的弊端。

HttpUnit让测试者可以通过Java类和服务器进行交互,并且将服务器端的响应当作文本或者DOM对象进行处理。HttpUnit还提供了一个模拟Servlet容器,让你可以不需要发布Servlet,就可以对Servlet的内部代码进行测试。

为了让HtpUnit正常运行,需要安装JDK1.3.1或者以上版本。

Automated testing is a great way to ensure that code being maintained works. The Extreme Programming (XP) methodology relies heavily on it, and practitioners have available to them a range of testing frameworks, most of which work by making direct calls to the code being tested. But what if you want to test a web application? Or what if you simply want to use a web-site as part of a distributed application?

In either case, you need to be able to bypass the browser and access your site from a program. HttpUnit makes this easy. Written in Java, HttpUnit emulates the relevant portions of browser behavior, including form submission, JavaScript, basic http authentication, cookies and automatic page redirection, and allows Java test code to examine returned pages either as text, an XML DOM, or containers of forms, tables, and links. When combined with a framework such as JUnit, it is fairly easy to write tests that very quickly verify the functioning of a web site.

The same techniques used to test web sites can be used to test and develop servlets without a servlet container using ServletUnit, included in the download.

HTTPUnit的工作原理:

HttpUnit通过模拟浏览器的行为,处理页面框架(frames),cookies,页面跳转(redirects)等。通过HttpUnit提供的功能,你可以和服务器端进行信息交互,将返回的网页内容作为普通文本、XML DOM对象或者是作为链接、页面框架、图像、表单、表格等的集合进行处理。可以结合使用JUnit框架进行测试。还可以导向一个新的页面,然后进行新页面的处理,这个功能使你可以处理一组在一个操作链中的页面。

WebConversation类模拟浏览器与网站服务器进行交互

WebRequest类发送请求

WebResponse类接收响应

getText

getURL

getTables

getLinks、getLinkWith

getForms

可以测试:

1、测试某个指定的页面是否存在

2、测试页面跳转是否正确

3、测试页面内容是否正确

4、测试链接

5、测试表单

HTTPUnit和其他商业工具的对比:

商业工具一般使用记录、回放的功能来实现测试,但是这里有个缺陷,就是当页面设计被修改以后,这些被记录的行为就不能重用了,需要重新录制才能继续测试。举个例子:如果页面上有个元素最先的设计是采用单选框,这个时候你开始测试,那么这些工具记录的就是你的单项选择动作,但是如果你的设计发生了变化,比如说我改成了下拉选择,或者使用文本框接受用户输入,这时候,你以前录制的测试过程就无效了,必须要重新录制。

而HttpUnit因为关注点是这些控件的内容,所以不管你的外在表现形式如何变化,都不影响你已确定测试的可重用性。

目前最新版本:

下载并解压HttpUnit之后,目录结构应该如下所示:

httpunit

+--- jars //包含创建、测试以及运行HttpUnit所必须的jar

|

+--- lib // 包含HttpUnit jar

|

+--- doc //文档

| |

| +--- tutorial //基于servlet web网站的测试优先开发的简单教程

| |

| +--- api // javadoc

| |

| +--- manual // 用户手册

|

+--- examples // 采用HttpUnit编写的一些示例程序

|

+--- src // HttpUnit 源代码

|

+--- test // HttpUnit单元测试的一些很好的例子

只有lib和jars两个目录对运行HttpUnit是必须的。至少你必须将HttpUnit jar添加到系统的classpath,而其他的一些jar均为可选。

HttpUnit包括许多可选的功能。如果你并不需要这些功能,则不必在classpath中包含相应的库但至少你必须有一个HTML解析器(JTidy和NekoHTML都可被支持)和一个与jaxp 兼容的解析器(在发行版中包含了xerces 2.2)。

直接获取页面内容

The very first step in any interaction with a web site is to obtain a start page. To do this, we create a WebConversation object to play the role

of the web browser. This object will store browser state such a cookies, windows, and so on. We then ask for the page by specifying the desired URL:

easy to search for particular strings on the page, if that is desired.

在Eclipse中使用HttpUnit:

import java.io.IOException;

import org.xml.sax.SAXException;

import com.meterware.httpunit.*;

public class Test {

/**

*@param args

*/

public static void main(String[] args) {

WebConversation wc = new WebConversation();

WebResponse wr = null;

try {

wr = wc.getResponse( "http://127.0.0.1:1080/WebTours/" );

System.out.println( wr.getText() );

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

}

}

通过Get方法访问页面并且加入参数

例:

System.out.println("向服务器发送数据,然后获取网页内容:");

//建立一个WebConversation实例

WebConversation wc = new WebConversation();

//向指定的URL发出请求

WebRequest req = new

GetMethodWebRequest( "http://127.0.0.1:1080/WebTours/nav.pl");

//给请求加上参数

req.setParameter("in","home");

//获取响应对象

WebResponse resp;

try {

resp = wc.getResponse( req );

//用getText方法获取相应的全部内容

//用System.out.println将获取的内容打印在控制台上

System.out.println( resp.getText() );

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

测试WebTours的例子:

import java.io.IOException;

import org.xml.sax.SAXException;

import com.meterware.httpunit.*;

public class Test {

/**

* @param args

*/

public static void main(String[] args) {

WebConversation wc = new WebConversation();

WebResponse wr = null;

String userSession = "" ;

try {

wr = wc.getResponse( "http://127.0.0.1:1080/WebTours/" );

wr = wc.getResponse("http://127.0.0.1:1080/WebTours/header.html");

wr = wc.getResponse("http://127.0.0.1:1080/WebTours/welcome.pl?signOff=1");

//wr = wc.getResponse("http://127.0.0.1:1080/WebTours/images/hp_logo.png");

//wr = wc.getResponse("http://127.0.0.1:1080/WebTours/images/webtours.png");

wr = wc.getResponse("http://127.0.0.1:1080/WebTours/nav.pl?in=home");

String responseText = wr.getText() ;

System.out.println( responseText );

String toFind = "userSession value=";

int LB = responseText.indexOf(toFind) + toFind.length();

int RB = responseText.indexOf(">",LB);

userSession = responseText.substring(LB,RB);

System.out.println("userSession value = " + userSession);

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

System.out.println("向服务器发送数据,然后获取网页内容:");

//建立一个WebConversation实例

//WebConversation wc = new WebConversation();

//向指定的URL发出请求

WebRequest req = new GetMethodWebRequest( "http://127.0.0.1:1080/WebTours/login.pl");

//给请求加上参数

req.setParameter("userSession",userSession);

req.setParameter("username","jojo");

req.setParameter("password","bean");

req.setParameter("JSFormSubmit","off");

req.setParameter("login.x","54");

req.setParameter("login.y","13");

//获取响应对象

WebResponse resp;

try {

resp = wc.getResponse( req );

//用getText方法获取相应的全部内容

//用System.out.println将获取的内容打印在控制台上

System.out.println( resp.getText() );

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

}

}

通过Post方法访问页面并且加入参数

例:

System.out.println("向服务器发送数据,然后获取网页内容:");

//建立一个WebConversation实例

//WebConversation wc = new WebConversation();

//向指定的URL发出请求

WebRequest req = new

PostMethodWebRequest( "http://127.0.0.1:1080/WebTours/login.pl");

//给请求加上参数

req.setParameter("userSession",userSession);

req.setParameter("username","jojo");

req.setParameter("password","bean");

req.setParameter("JSFormSubmit","off");

req.setParameter("login.x","54");

req.setParameter("login.y","13");

//获取响应对象

WebResponse resp;

try {

resp = wc.getResponse( req );

//用getText方法获取相应的全部内容

//用System.out.println将获取的内容打印在控制台上

System.out.println( resp.getText() );

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

可以看到,使用Get、Post方法访问页面的区别就是使用的请求对象不同。

注,Get和Post的区别:

1.HTTP请求格式:

[]

在HTTP请求中,第一行必须是一个请求行(request line),用来说明请求类型、要访问的资源以及使用的HTTP版本。紧接着是一个首部(header)小节,用来说明服务器要使用的附加信息。在首部之后是一个空行,再此之后可以添加任意的其他数据[称之为主体(body)]。

2.GET与POST区别

HTTP定义了与服务器交互的不同方法,最基本的方法是 GET 和 POST.

HTTP-GET和HTTP-POST是使用HTTP的标准协议动词,用于编码和传送变量名/变量值对参数,并且使用相关的请求语义。每个HTTP-GET和HTTP-POST都由一系列HTTP请求头组成,这些请求头定义了客户端从服务器请求了什么,而响应则是由一系列HTTP应答头和应答数据组成,

如果请求成功则返回应答。

HTTP-GET以使用MIME类型application/x-www-form-urlencoded的urlencoded文本的格式传递参数。Urlencoding是一种字符编码,保证被传送的参数由遵循规范的文本组成,例如一个空格的编码是"%20"。附加参数还能被认为是一个查询字符串。

与HTTP-GET类似,HTTP-POST参数也是被URL编码的。然而,变量名/变量值不作为URL的一部分被传送,而是放在实际的HTTP请求消息内部被传送。

(1)get是从服务器上获取数据,post是向服务器传送数据。

(1)在客户端,Get方式在通过URL提交数据,数据在URL中可以看到;POST方式,数据放置在HTML HEADER内提交。

(2)对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。

(2)GET方式提交的数据最多只能有1024字节,而POST则没有此限制。

(3)安全性问题。正如在(1)中提到,使用Get 的时候,参数会显示在地址栏上,而Post 不会。所以,如果这些数据是中文数据而且是非敏感数据,那么使用get;如

果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用post为好。

注:所谓安全的意味着该操作用于获取信息而非修改信息。幂等的意味着对同一URL 的多个请求应该返回同样的结果。完整的定义并不像看起来那样严格。换句话说,GE

T 请求一般不应产生副作用。从根本上讲,其目标是当用户打开一个链接时,她可

以确信从自身的角度来看没有改变资源。比如,新闻站点的头版不断更新。虽然第

二次请求会返回不同的一批新闻,该操作仍然被认为是安全的和幂等的,因为它总

是返回当前的新闻。反之亦然。POST 请求就不那么轻松了。POST 表示可能改变

服务器上的资源的请求。仍然以新闻站点为例,读者对文章的注解应该通过POST

请求实现,因为在注解提交之后站点已经不同了(比方说文章下面出现一条注解)。下面举一个简单的例子来说明它们的区别:



<% If Request.QueryString("Text") <> "" Then %>

通过get方式传递的字符串是: "<%= Request.QueryString("Text") %>"
<% End If %>

<% If Request.Form("Text") <> "" Then %>

通过Post方式传递的字符串是: "<%= Request.Form("Text") %>"

<% End If %>

处理页面中的链接

找到页面中的某一个链接,然后模拟用户的单击行为,获得它指向文件的内容。

例:

public static void Link(){

System.out.println("获取页面中链接指向页面的内容:");

//建立一个WebConversation实例

WebConversation wc = new WebConversation();

//获取响应对象

WebResponse resp;

try {

resp = wc.getResponse( "http://127.0.0.1:1080/WebTours/" );

resp =

wc.getResponse("http://127.0.0.1:1080/WebTours/header.html");

resp =

wc.getResponse("http://127.0.0.1:1080/WebTours/welcome.pl?signOff=tru e");

resp =

wc.getResponse("http://127.0.0.1:1080/WebTours/nav.pl?in=home");

resp =

wc.getResponse("http://127.0.0.1:1080/WebTours/home.html");

//String respText = resp.getText();

//System.out.println(respText);

//获得页面链接对象

WebLink[] link = resp.getLinks();

String linkURL = link[1].getURLString();

String linkName = link[1].getName();

String linkText = link[1].getText();

String linkID = link[1].getID();

System.out.println("linkURL:"+linkURL +"\n");

System.out.print("linkName:"+linkName+"\n");

System.out.print("linkText:"+linkText+"\n");

System.out.print("linkID:"+linkID+"\n");

//模拟用户单击事件

link[0].click();

//获得当前的响应对象

WebResponse nextLink = wc.getCurrentPage();

//用getText方法获取相应的全部内容

//用System.out.println将获取的内容打印在控制台上

System.out.println( nextLink.getText() );

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

}

处理页面中的表格

表格是用来控制页面显示的常规对象,在HttpUnit中使用数组来处理页面中的多个表格,你可以用resp.getTables()方法获取页面所有的表格对象。他们依照出现在页面中的顺序保存在一个数组里面。

例:

try {

resp =

wc.getResponse( "http://127.0.0.1:1080/WebTours/welcome.pl?page=itine rary" );

resp =

wc.getResponse( "http://127.0.0.1:1080/WebTours/nav.pl?page=menu&in=i tinerary" );

resp =

wc.getResponse( "http://127.0.0.1:1080/WebTours/itinerary.pl" );

//获得对应的表格对象

WebTable webTable = resp.getTables()[0];

int rowCount = webTable.getRowCount();

System.out.println("\n表格行数:" + rowCount);

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

处理页面中的表单

表单是用来接受用户输入,也可以向用户显示用户已输入信息(如需要用户修改数据时,通常会显示他以前输入过的信息),在HttpUnit中使用数组来处理页面中的多个表单,你可以用resp.getForms()方法获取页面所有的表单对象。他们依照出现在页面中的顺序保存在一个数组里面。

例:

WebRequest reqs = new

GetMethodWebRequest( "http://127.0.0.1:1080/WebTours/welcome.pl?page= search");

reqs = new

GetMethodWebRequest( "http://127.0.0.1:1080/WebTours/nav.pl?page=menu &in=flights");

reqs = new

GetMethodWebRequest( "http://127.0.0.1:1080/WebTours/reservations.pl? page=welcome");

WebResponse resps = null;

try {

resps = wc.getResponse( reqs );

System.out.println( resps.getText() );

//获得表单对象

WebForm[] webForms = resps.getForms();

//获得表单中所有控件的名字

String[] pNames = webForms[0].getParameterNames();

int i = 0;

int m = pNames.length;

//循环显示表单中所有控件的内容

while(i

System.out.println("第"+(i+1)+"个控件的名字是

"+pNames[i]+",里面的内容是"

+webForms[0].getParameterValue(pNames[i]));

++i;

}

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

HttpUnit+JUnit

在Eclipse中创建JUnit测试用例,加入对httpunit包的引入,获取页面中表格的内容并通过assertEquals来检查内容是否与预期值一致。

import java.io.IOException;

import org.xml.sax.SAXException;

import com.meterware.httpunit.PostMethodWebRequest;

import com.meterware.httpunit.WebConversation;

import com.meterware.httpunit.WebRequest;

import com.meterware.httpunit.WebResponse;

import com.meterware.httpunit.WebTable;

import static org.junit.Assert.*;

import org.junit.Test;

public class TestCase1 {

@Test

public void HttpUnit_JUnit_Test1(){

System.out.println("获取页面中表格的内容并且进行测试:");

WebConversation wc = new WebConversation();

WebResponse wr = null;

String userSession = "" ;

try {

wr = wc.getResponse( "http://127.0.0.1:1080/WebTours/" );

wr =

wc.getResponse("http://127.0.0.1:1080/WebTours/header.html");

wr =

wc.getResponse("http://127.0.0.1:1080/WebTours/welcome.pl?signOff=1") ;

wr =

wc.getResponse("http://127.0.0.1:1080/WebTours/nav.pl?in=home");

String responseText = wr.getText() ;

System.out.println( responseText );

String toFind = "userSession value=";

int LB = responseText.indexOf(toFind) + toFind.length();

int RB = responseText.indexOf(">",LB);

userSession = responseText.substring(LB,RB);

System.out.println("userSession value = " + userSession);

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

WebRequest req = new

PostMethodWebRequest( "http://127.0.0.1:1080/WebTours/login.pl");

req.setParameter("userSession",userSession);

req.setParameter("username","jojo");

req.setParameter("password","bean");

req.setParameter("JSFormSubmit","off");

req.setParameter("login.x","54");

req.setParameter("login.y","13");

WebResponse resp = null;

try {

resp = wc.getResponse( req );

System.out.println( resp.getText() );

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

try {

resp =

wc.getResponse( "http://127.0.0.1:1080/WebTours/welcome.pl?page=itine rary" );

resp =

wc.getResponse( "http://127.0.0.1:1080/WebTours/nav.pl?page=menu&in=i tinerary" );

resp =

wc.getResponse( "http://127.0.0.1:1080/WebTours/itinerary.pl" );

//获得对应的表格对象

WebTable webTable = resp.getTables()[0];

int rowCount = webTable.getRowCount();

System.out.println("\n表格行数:" + rowCount);

//将表格对象的内容传递给字符串数组

String[][] datas = webTable.asText();

//对表格内容进行测试

String expect = "A total of 1 scheduled flights.";

assertEquals(expect,datas[4][0].toString());

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

对Servlet进行测试

除了对页面内容进行测试外,有时候(比如开发复杂的Servlets的时候),你需要对Servlet 本身的代码块进行测试,这时候你可以选择HttpUnit,它可以提供一个模拟的Servlet容器,让你的Servlet代码不需要发布到Servlet容器(如tomcat)就可以直接测试。

使用httpunit测试Servlet时,请创建一个ServletRunner的实例,他负责模拟Servlet容器环境。如果你只是测试一个Servlet,你可以直接使用registerServlet方法注册这个Servlet,如果需要配置多个Servlet,你可以编写自己的web.xml,然后在初始化ServletRunner的时候将它的位置作为参数传给ServletRunner的构造器。

在测试Servlet时,应该记得使用ServletUnitClient类作为客户端,他和前面用过的WebConversation差不多,都继承自WebClient,所以他们的调用方式基本一致。要注意的差别是,在使用ServletUnitClient时,他会忽略URL中的主机地址信息,而是直接指向他的ServletRunner实现的模拟环境。

简单例子:

1、创建被测试的Servlet:

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloWorldExample extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("");

out.println("");

String title = "helloworld.title";

out.println("" + title + "");

out.println("");

out.println("");

// note that all links are created to be relative. this

// ensures that we can move the web application that this

// servlet belongs to to a different place in the url

// tree and not have any harmful side effects.

// XXX

// making these absolute till we work out the

// addition of a PathInfo issue

out.println("");

out.println("

"width=24 align=right border=0 alt=\"view

code\">");

out.println("");

out.println("

"width=24 align=right border=0 alt=\"return\">"); out.println("

" + title + "

");

out.println("");

out.println("");

}

}

2、编写HttpUnit测试用例对Servlet进行测试:

public static void ServletTest(){

//创建Servlet的运行环境

ServletRunner sr = new ServletRunner();

//向环境中注册Servlet

sr.registerServlet( "HelloWorldExample",

HelloWorldExample.class.getName() );

//创建访问Servlet的客户端

ServletUnitClient sc = sr.newClient();

//发送请求

WebRequest request = new

GetMethodWebRequest( "http://127.0.0.1:8080/HelloWorldExample" );

//获得模拟服务器的信息

WebResponse response;

try {

response = sc.getResponse( request );

//将获得的结果打印到控制台上

System.out.println(response.getText());

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

}

}

测试Servlet内部行为

对于开发者来说,仅仅测试请求和返回信息是不够的,所以HttpUnit提供的ServletRunner 模拟器可以让你对被调用Servlet内部的行为进行测试。和简单测试中不同,这里使用了InvocationContext获得该Servlet的环境,然后你可以通过InvocationContext对象针对request、response等对象或者是该Servlet的内部行为(非服务方法)进行操作。

1、被测试Servlet代码:

RequestParamExample.java:

RequestParamExample.java

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

import util.HTMLFilters;

/**

*Example servlet showing request headers

*

*@author James Duncan Davidson

*/

public class RequestParamExample extends HttpServlet {

//ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");

public void MyInit()

{

S ystem.out.println("MyInit Method Invoke!");

}

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("");

out.println("");

out.println("");

//String title = rb.getString("requestparams.title");

String title = "requestparams.title";

out.println("" + title + "");

out.println("");

out.println("");

// img stuff not req'd for source code html showing // all links relative

// XXX

// making these absolute till we work out the

// addition of a PathInfo issue

out.println("");

out.println("

"width=24 align=right border=0 alt=\"view

code\">");

out.println("");

out.println("

"width=24 align=right border=0 alt=\"return\">");

out.println("

" + title + "

");

String firstName = request.getParameter("firstname");

String lastName = request.getParameter("lastname");

//out.println(rb.getString("requestparams.params-in-req") +

"
");

out.println("requestparams.params-in-req" + "
");

if (firstName != null || lastName != null) {

//out.println(rb.getString("requestparams.firstname"));

out.println("requestparams.firstname");

out.println(" = " + HTMLFilters.filter(firstName) + "
");

//out.println(rb.getString("https://www.doczj.com/doc/cd79241.html,stname"));

out.println("https://www.doczj.com/doc/cd79241.html,stname");

out.println(" = " + HTMLFilters.filter(lastName));

} else {

//out.println(rb.getString("requestparams.no-params"));

out.println("requestparams.no-params");

}

out.println("

");

out.print("

out.print("RequestParamExample\" ");

out.println("method=POST>");

//out.println(rb.getString("requestparams.firstname"));

out.println("requestparams.firstname");

out.println("");

out.println("
");

//out.println(rb.getString("https://www.doczj.com/doc/cd79241.html,stname"));

out.println("https://www.doczj.com/doc/cd79241.html,stname");

out.println("");

out.println("
");

out.println("");

out.println("

");

out.println("");

out.println("");

}

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

{

doGet(request, response);

}

}

HTMLFilters.java:

相关主题
文本预览
相关文档 最新文档