Checking a Static Web Page
Problem
You want to test for the existence of a static web page.
Solution
Write a JUnit test fixture, and then use classes in the
com.meterware.httpunit
package to connect to the
web page.
Discussion
When starting a brand new web application, verify that you can connect to the home page before doing anything else. This is the simplest test that you can write, and only takes a few lines of code. Example 5-1 shows how to do it.
Example 5-1. Testing for a static web page
package com.oreilly.javaxp.httpunit;import com.meterware.httpunit.*;
import junit.framework.TestCase; public class TestNewsletter extends TestCase { public TestNewsletter(String name) { super(name); } public void testIndexPageExists( ) throws Exception {WebConversation webConversation = new WebConversation( );
WebRequest request =
new GetMethodWebRequest("http://localhost:8080/news");
WebResponse response =
webConversation.getResponse(request);
} }
The
WebConversation
class is described as HttpUnit’s replacement for the
web browser. WebConversation
is the client,
allowing you to send requests and obtain responses from a web server.
Use the
GetMethodWebRequest
class to issue an HTTP GET
request, specifying a URL in the constructor. This mimics a user
typing in a URL in their web browser. Then call the
getResponse( )
method to actually issue the
request and retrieve the web page. If getResponse( )
cannot find the web page, it throws a new instance of
HttpNotFoundException
. As customary in ...
Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.