(转载)JWebUnit做Web项目自动化测试

原址:http://blog.csdn.net/plainfield/archive/2007/07/02/1675546.aspx

JwebUnit加构在HttpUnit上,实际上也可以这么说是HttpUnit的高一层API封装,用户使用它不必像使用HttpUnit那么麻烦。一直到今天,JwebUnit已经不更新了,HttpUnit仍旧蓬勃的发展着,作为我曾经深入使用过的测试工具,我觉得非常有必要写点什么东西出来。

如果你想下载 JWebUnit 可以点击下面这个链接 http://sourceforge.net/projects/jwebunit

JWebUnit的编译需要下面几个包的支持:

HttpUnit Java library for the automatic stimulation and testing of web applications. 下载

Rhino Javascript implementation in Java used by httpunit. Only needed if javascript in target application must be tested.下载

nekohtml Java html parser and beautifier used by httpunit.下载

JUnit Java unit testing framework.下载

Apache XML API Common XML stuff needed by Tidy/HttpUnit.下载

Xerces xml parser Needed for Httpunit/neko.下载

快速应用

jWebUnit大致有两种方式建立测试用例:继承模式和委托模式,下面这种是用户测试用例代码使用继承模式继承jWebUnit提供的WebTestCase类,该类继承与junit.framework.TestCase类,代码示例如下:

import net.sourceforge.jwebunit.WebTestCase;

public class ExampleWebTestCase extends WebTestCase {
public ExampleWebTestCase(String name) {
    super(name);
}
}

委托模式的实现比上面的正统方式实现曲折了一点,代码示例如下:

import junit.framework.TestCase;
import net.sourceforge.jwebunit.WebTester;

public class ExampleWebTestCase extends TestCase {
private WebTester tester;

public ExampleWebTestCase(String name) {
    super(name);
    tester = new WebTester();
}
}

用户测试用例代码继承了junit.framework.TestCase类,在该类的全局变量里声明了一个WebTester类,该类属于jwebunit封装了一些拟人的Web操作动作等,在ExampleWebTestCase 构造方法中将WebTester实例化。委托模式有个好处,代码表现上很干净,测试动作和被测试业务代码将被表现的异常清晰,有利于后期的测试开发迭代。

触摸我们的第一个被测试网站

如果我的被测试Web网站的地址为:http://127.0.0.1/hello,那么我们可以这样让jwebunit接触它,示例代码如下:

public ExampleWebTestCase(String name) {
super(name);
getTestContext().setBaseUrl("http://127.0.0.1/hello");
}

其实Junit里面提供了测试前置资源设置方法,我们也可以这样写:

public ExampleWebTestCase(String name) {
super(name);
}

public void setUp() throws Exception {
getTestContext().setBaseUrl("http://127.0.0.1/hello");
}

这样做的好处是让资源和被测试代码分离,不要相互干扰。

上面的setBaseUrl("http://127.0.0.1/hello")只是帮助jwebunit指定到了被测试项目的位置,大部分网站根据应用服务器设置会自动让这样的访问定位到某页面上,例如:http://127.0.0.1/hello/index.jsp。如果我们想明确指定某个页面进入,那么你需要这么做,示例代码如下:

beginAt("/index.jsp");

这样,jwebunit就得到了明确的测试切入页面,测试开始了!

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/plainfield/archive/2007/07/02/1675546.aspx

原文地址:https://www.cnblogs.com/huapox/p/3509885.html