Testing Secure Pages

Problem

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

Solution

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

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 {
        this.webConversation.getResponse(
                "http://localhost:8080/news/viewSubscribers");
        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");
    this.webConversation.getResponse(
            "http://localhost:8080/news/viewSubscribers");
}

J2EE web applications support numerous types of authentication; this recipe ...

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.