Chapter 5. Testing Web Sites with HTTPUnit
The ability to test Java classes with a tool like JUnit is of great utility and importance. Because many applications are deployed as Web sites, it would also be tremendously useful to automate the testing of such applications. Manual testing of Web sites consists of a user interacting with the site through a browser, so any automated testing tool should mimic this interaction as closely as possible.JUnit can be used as a first step toward this ideal testing tool. Writing a JUnit test is a matter of writing a Java class, so anything that can be expressed in Java can be tested. Listing 5.1 demonstrates this flexibility by showing a JUnit test that ensures that the string "Hello" appears on the first page of the application.
Listing 5.1. A test for a Web page
This example works, but it is clearly less than optimal. There are nine lines of code for one single line of meaningful testing, which is a poor ratio. The kinds of test that can be done this way are also very limited. There is no easy way to test for structural elements on a page such as the presence of a particular link, form, or button. Testing a page that uses JavaScript is completely out of the question.
package com.awl.toolbook.chapter05;
import junit.framework.*;
import java.io.*;
import java.net.*;
public class SimpleWebTest extends TestCase {
public void testPage() throws Exception {
URL url = new URL(
"http://localhost:8080/toolbook/"+
"chapter05/sample.jsp");
InputStream in = url.openStream();
byte data[] = new byte[1024];
StringBuffer buffy = new StringBuffer();
int count;
while((count = in.read(data)) > 0) {
buffy.append(new String(data,0,count));
}
in.close();
assertTrue(buffy.toString().indexOf("Hello") != 0);
}
}