Testing Cookies

Problem

You want to create cookies and test for the existence of cookies.

Solution

Use WebConversation’s addCookie( ) method to create new cookies, and its getCookieValue( ) method to retrieve cookie values.

Discussion

Cookies are little pieces of information that web applications store on the client browser’s machine. Cookies allow web sites to maintain state information as you view different web pages. HttpUnit creates cookies and retrieve cookies using methods on the WebConversation class.

For the sake of an example, let’s look at a simple JSP that uses cookies. Example 5-12 shows a JSP that creates a new cookie and then displays the array of cookies from the client.

Example 5-12. A JSP that generates and displays cookies

                  <%-- generate a cookie --%>
<%
   Cookie cookie = new Cookie("customerId", "12345");
   response.addCookie(cookie);
%>

<html>
  <head><title>Cookie Demo</title></head>

  <body>
    <h1>Cookies in this request</h1>
    <table>
      <tr>
        <th>Cookie Name</th>
        <th>Value</th>
      </tr>

    <%-- print all of the cookies for this request --%>
    <% Cookie[] cookies = request.getCookies(  );
      int numCookies = (cookies != null) ? cookies.length : 0;
      for (int i=0; i<numCookies; i++) { %>
        <tr>
          <td><%= cookies[i].getName(  ) %></td>
          <td><%= cookies[i].getValue(  ) %></td>
        </tr>
   <% } %>

    </table>
  </body>
</html>

The unit test, shown in Example 5-13, works with the JSP shown in Example 5-12. The unit test accomplishes two tasks. First, it shows how you can create new cookies from your own unit tests. ...

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.