From Gossip@caterpillar

JUnit Gossip: 簡介 HttpUnit

HttpUnit雖然也有Unit的名字,但它本身並不是測試工具,所謂不是測試工具的意思是,它不提供任何的測試或斷言方法,正確來說,它是測試時的輔 助工具,它協助您進行HTTP請求響應,讓您在請求上加上參數、設置Cookie等,它將回應的訊息加以剖析整理,您可以從它提供的物件上得到分析後的表 頭(Header)、表單(Form)、表格(Table)等等,這些都有利於您進行測試時省去一些撰寫分析工具的功夫。

您可以至 HttpUnit 官方網站 下載檔案,在下載並解開檔案後,您可以在 lib 目錄下找到 httpunit.jar,將之加至您的CLASSPATH中,如果用到一些剖析HTML的方法,您還會需要HTML剖析器,您可以使用 JTidy,它的 jar 檔案可以在解開後的 jars 目錄下找到 Tidy.jar 檔案,該目錄下還有一些相關的 jar 檔案,如果您有需要與HttpUnit的結合的功能,可以在這個目錄下取得這些相依檔案。

來實際撰寫一個簡單的測試程式:

  • FirstHttpUnitTest.java
package onlyfun.caterpillar.test;

import java.io.IOException;
import java.net.MalformedURLException;

import org.xml.sax.SAXException;

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

import junit.framework.TestCase;

public class FirstHttpUnitTest extends TestCase {

public void testCaterpillarOnlyfun()
throws MalformedURLException,
IOException,
SAXException {
WebConversation webConversation =
new WebConversation();
WebRequest request =
new GetMethodWebRequest(
"http://caterpillar.onlyfun.net/phpBB2/");
WebResponse response =
webConversation.getResponse(request);
assertTrue(response.getTitle().startsWith(
"caterpillar.onlyfun.net"));
}

public static void main(String[] args) {
junit.swingui.TestRunner.run(
FirstHttpUnitTest.class);
}
}

WebConversation是HttpUnit的中心,您使用它來展開與HTTP相關的協議對話,您使用 WebRequest設置相關的請求參數,之後用WebConversation連接目的網頁,然後得到回應WebResponse,之後您可以從這個物 件上得到一些剖析過後的訊息,例如使用getTitle()方法可以取得<title>與</title>之間設置的標題文字。