Testing HTML Tables

Problem

You want to test the contents of one or more HTML tables.

Solution

Use com.meterware.httpunit.WebTable and com.meterware.httpunit.TableCell to analyze the content of tables in your HTML pages.

Discussion

HttpUnit provides a simple API for parsing HTML and obtaining tables, cells, and cell content. Figure 5-1 shows a sample web page for the code shown in this recipe.

Sample HTML tables

Figure 5-1. Sample HTML tables

Example 5-2 demonstrates how you can test the content of the top table. In this example, the table is located based on the text found within its first cell using the WebResponse.getTableStartingWith( ) method.

Example 5-2. Simple table testing

    public void testPersonTable(  ) throws Exception {
        WebConversation webConversation = new WebConversation(  );
        WebResponse response = webConversation.getResponse(
                "http://localhost:8080/news/sampleTable.html");

        // get the HTML table with 'First Name' as the text of its
        // first non-blank cell
        WebTable table = response.getTableStartingWith("First Name");
        assertEquals("column count", 2, table.getColumnCount(  ));
        assertEquals("row count", 3, table.getRowCount(  ));

        // get the cell at row 2, column 0
        TableCell cell = table.getTableCell(2, 0);
        assertEquals("cell text", "Tanner", cell.asText(  ));
    }

Once the WebTable object is located, the test uses various methods on the WebTable class to obtain the number of rows and columns, as well ...

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.