Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Design Pattern & UML  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 【原创】HttpUnit轻松上手
daviszw





发贴: 11
积分: 20
于 2004-08-12 15:44 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
HttpUnit从根本上说并不是单元测试。它更接近于功能测试。使用HttpUnit编写的Web应用程序测试并不对应用程序代码的片段做测试,而是在外部询问Web服务器并检查接收的响应。
HttpUnit的WebClient(抽象类)/WebConversation扮演了诸如Web浏览器之类的角色: 维护客户端状态——包括诸如cookies、相关URL以及页面框架设置之类的持续响应头,并且允许某个用户发送请求到指定资源和得到响应。
下面这个例子假设访问一个需要登陆的站点,对于登陆部分所做的测试。

import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;

import junit.framework.TestCase;

/**
* @author davis
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TestSample extends TestCase {

  WebConversation conversation;
  
  /*
   * @see TestCase#setUp()
   */
  protected void setUp() throws Exception {
    conversation = new WebConversation();    
  }
  
  private WebResponse goToPrivatePage() throws Exception {
    return conversation.getResponse("http://localhost:8080/myreport/reportGroup.action");
  }
  
  public void testLogin() throws Exception {
    WebResponse response = this.goToPrivatePage();
    //验证是否在登陆页面
    assertLoginPage(response);
    //使用不正确的用户名和密码登陆
    response = login(response, "xxx", "xxx");
    assertLoginPage(response);
    
    //检查错误信息
    String pageStr = response.getText();
    assertTrue(pageStr.indexOf("用户名和密码不正确") > -1);
    
    //正确登陆
    response = login(response, "test", "test");
//检查已经不在登陆页面
    assertTrue(!response.getTitle().equals("Login"));
  }
  
  public void assertLoginPage(WebResponse response) throws Exception {
    //验证页面的标题一般是一个快速的验证是否在正确页面的方法
    assertEquals("成功登陆", "Login", response.getTitle());
  }
  
  public WebResponse login(WebResponse loginPage, String userName, String pass) throws Exception {
    WebForm form = loginPage.getForms()[0];
    WebRequest loginRequest = form.getRequest();
    loginRequest.setParameter("userName", userName);
    loginRequest.setParameter("password", pass);
    return conversation.getResponse(loginRequest);
  }
}

然后在Eclipse中将这个测试Run/Junit Test就可以了,是不是很简单Smile

btw:最新的HttpUnit 1.5.4已经支持JavaScript了。




flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923