Submitting Form Data

Problem

You want to write a test that submits your HTML forms and verifies the forms functionality.

Solution

Set parameters on the WebForm using its setParameter( ) method. Then simulate clicking a button by asking for one of the form’s buttons and submitting it using the WebConversation instance.

Discussion

You fill in form field values using the setParameter( ) method on a WebForm instance. This simulates what the user would do if he was filling out a form in a web browser. You then ask the form for a WebRequest object, passing in the name of one of the submit buttons. All of this is shown in Example 5-9.

Example 5-9. Submitting a form

public void testSubmitSubscriptionWithoutRequiredField(  )
        throws Exception {
    WebForm form = getBlankSubscriptionForm(  );
    form.setParameter("nameField", "Eric Burke");
    WebRequest request = form.getRequest("subscribeBtn");
    // Submit the page. The web app should return us right back to
    // the subscription page because the Email address is not specified
    WebResponse response = this.webConversation.getResponse(request);

    // make sure the user is warned about the missing field
    String pageText = response.getText(  );
    assertTrue("Required fields warning is not present",
            pageText.indexOf("Email address is required") > -1);

    // make sure the nameField has the original text
    form = response.getFormWithID("subscriptionForm");
    assertEquals("Name field should be pre-filled",
            "Eric Burke", form.getParameterValue("nameField"));
}

The comments in Example ...

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.