5.1 Introduction

HttpUnit, available from http://www.httpunit.org, is an open source Java library for programmatically interacting with HTTP servers. With HttpUnit, your Java programs can access servers directly, without the need for a browser. HttpUnit provides an API for parsing HTML, submitting forms, following hyperlinks, setting cookies, and performing many other tasks normally associated with web browsers. It also includes a class library for direct manipulation of servlets, sometimes bypassing the need to start a web server.

Despite its name, HttpUnit is not a testing tool. Instead, it provides an API for interacting with HTML and HTTP servers. You normally think of HttpUnit as a testing tool, however, because you use HttpUnit in conjunction with JUnit to write tests. JUnit defines the testing framework and your testXXX( ) methods use the HttpUnit API to access and test web pages.

Tests written with HttpUnit are usually more like "integration" tests than "unit" tests. A unit test normally tests a single method or class in isolation, while HttpUnit tests invoke HTTP servers across a network connection.

Using HttpUnit in combination with JUnit is the focus of the recipes in this chapter. The recipes are presented in order as portions of a simple web application developed using a test-first approach. If the web application were complete, it would allow users to subscribe and unsubscribe from a newsletter. It would also allow administrators to view the complete list of newsletter subscribers, but only after providing a username and password.

HttpUnit cannot test JavaScript. You might consider JsUnit, available at http://sourceforge.net/projects/jsunit/.