O'Reilly logo

Java Extreme Programming Cookbook by Brian M. Coyner, Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Testing a Form Tag and Refactoring Your Tests

Problem

You want to test for the existence of an HTML form.

Solution

Use the com.meterware.httpunit.WebForm class to test the form method and action.

Discussion

Adding HTML forms to a web application implies that the application is beginning to take on dynamic behavior. As your application gets more complex, you should continually refactor your tests in order to keep them as simple as possible. The solution outlined here shows how to test for an HTML form, as well as showing a refactored test fixture. Example 5-5 opens with a test for a basic HTML form.

Example 5-5. Refactored unit test

package com.oreilly.javaxp.httpunit;

import com.meterware.httpunit.*;
import junit.framework.TestCase;

public class TestNewsletter extends TestCase {
    private WebConversation webConversation;

    public TestNewsletter(String name) {
        super(name);
    }

    public void setUp(  ) throws Exception {
        this.webConversation = new WebConversation(  );
    }

    ...tests from earlier recipes are not shown here

    public void testSubscriptionForm(  ) throws Exception {
        WebForm form = getBlankSubscriptionForm(  );
        assertEquals("subscription form action",
                "subscription", form.getAction(  ));
        assertEquals("subscription form method",
                "post", form.getMethod().toLowerCase(  ));
    } private WebForm getBlankSubscriptionForm( ) throws Exception { WebResponse response = getBlankSubscriptionPage( ); return response.getFormWithID("subscriptionForm"); } private WebResponse getBlankSubscriptionPage( ) throws Exception ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required