HttpUnitとhtmlunit

JSF demoのテストコードでは、com.gargoylesoftware.htmlunit...というパッケージ名のクラスが使われていました。HttpUnit(http://www.httpunit.org/)というテストツールがあるのは知っていたのですが、htmlunitというテストツールもあったことを知りました。このツール、パッケージ名がcom.gargoylesoftwareなので売り物なのかと思いましたが、http://htmlunit.sourceforge.net/を見るとオープンソースApacheライセンスのツールでした。
htmlunitのページではHttpUnitはHTTPプロトコルをまねるものに対してhtmlunitWebブラウザをまねるものと説明されています。といってもhttpunitもHTML文書部分を解析できるので、どこらもできることはあまり変わらなさそうです。使い勝手はhtmlunitの方がいいかも。例えばテーブルですが、

●HttpUnitの場合

WebConversation wc = new WebConversation();
WebResponse resp =
    wc.getResponse("http://www.meterware.com/testpage.html");
String[][] colors = resp.getTables()[1].asText();
assertEquals("Name",  colors[0][0]);
assertEquals("Color", colors[0][1]);
assertEquals("gules", colors[1][0]);
assertEquals("red",   colors[1][1]);
assertEquals("sable", colors[2][0]);
assertEquals("black", colors[2][1]);
●htmlunitの場合

final WebClient webClient = new WebClient();
final HtmlPage page =
    (HtmlPage)webClient.getPage(new URL("http://foo.com"));

final HtmlTable table =
    (HtmlTable)page.getHtmlElementById("table1");
final List rows = table.getRows();
final Iterator rowIterator = rows.iterator();
while(rowIterator.hasNext()) {
    final HtmlTableRow row = (HtmlTableRow)iterator.next();
    System.out.println("Found row");
    final List cells = row.getCells();
    final Iterator cellIterator = cells.iterator();
    while(cellIterator.hasNext()) {
        final TableCell cell = (TableCell)cellIterator.next();
        System.out.println("   Found cell: "+cell.asText());
    }
}

のような感じになります。Javaに慣れていると配列よりもIterator方式のほうが使いやすいです。また、テーブルは全てが2次元配列になっているのではなく、http://www.j-wave.co.jp/contents/weather/point/p44131.htmlの表のように不規則な形をしているものもあります。HttpUnitの場合、getTables()[1].asText()とは違う方法で解析しないといけませんが、何行目のrowと何番目のcolでの指定が基本のようなので、テストプログラムのバグ取りに苦労しそう。