5.13 Testing Secure Pages

5.13.1 Problem

You want to test a page that requires a username and password for login.

5.13.2 Solution

Simulate HTTP BASIC authentication using WebConversation's setAuthorization( ) method.

5.13.3 Discussion

If your web application is configured to use HTTP BASIC authentication, you can use HttpUnit to simulate what happens when users enter a username and password in their browser. Our first unit test, shown next, verifies that the web application prevents unauthorized users from entering a secured web page.

public void testViewSubscribersWithoutLogin(  ) throws Exception {
    try {
        fail("viewSubscribers should require a login");
    } catch (AuthorizationRequiredException expected) {
        // ignored

If the web app prompts for a username and password, HttpUnit throws an AuthorizationRequiredException. Since this is the expected behavior, we catch the exception and ignore it. If the exception is not thrown, the test fails because the page is not secure.

The next test shows how to enter a username and password within a unit test. Behind the scenes, this simulates what happens when the user types in this information in the browser's login dialog.

public void testViewSubscribersWithLogin(  ) throws Exception {
    this.webConversation.setAuthorization("eric", "secret");

J2EE web applications support numerous types of authentication; this recipe shows how to use HttpUnit along with HTTP BASIC authentication. If you are using form-based authentication, you write your test just like you are testing any other HTML form.

5.13.4 See Also

See O'Reilly's Java Servlet Programming by Jason Hunter to learn more about servlet security.