How to verify that a cookie was sent from the Servlet back to the
client ?
J2EEUnit provides some helper code (j2eeunit.AssertUtils)
to retrieve cookies sent back in the HTTP response. For example,
you can use the following code (or check the J2EEUnit sample
application) :
Code in the class to unit test :
public class SampleServlet extends HttpServlet
[...]
/**
* Set a cookie for sending back to the client. This is to verify that
* it is possible with J2EEUnit to assert the cookies returned to the client
*
* @param theResponse the HTTP response
*/
public void setResponseCookie(HttpServletResponse theResponse)
{
Cookie cookie = new Cookie("responsecookie", "this is a response cookie");
cookie.setDomain("j2eeunit.sourceforge.net");
theResponse.addCookie(cookie);
}
Code in the J2EEUnit test class :
public class TestSampleServlet extends ServletTestCase
[...]
/**
* Test that it is possible to send back a Cookie and verify it on the
* client side.
*/
public void testReceiveCookie()
{
SampleServlet servlet = new SampleServlet();
servlet.setResponseCookie(response);
}
/**
* Test that it is possible to send back a Cookie and verify it on the
* client side.
*
* @param theConnection the HTTP connection that was used to call the
* server redirector. It contains the returned HTTP
* response.
*/
public void endReceiveCookie(HttpURLConnection theConnection)
{
Hashtable cookies = AssertUtils.getCookies(theConnection);
Vector list = (Vector)cookies.get("responsecookie");
assert(list.size() == 1);
ClientCookie cookie = (ClientCookie)list.elementAt(0);
assertEquals("responsecookie", cookie.getName());
assertEquals("this is a response cookie", cookie.getValue());
assertEquals("j2eeunit.sourceforge.net", cookie.getDomain());
}
How to write a unit test for a class that calls the
getServletContext() , getServletConfig(),
log() (i.e methods inherited from
GenericServlet) ?
Simply call the init(ServletConfig) method on your
servlet to test prior to calling the method to test.
Example (from the J2EEUnit sample application) :
/**
* Verify that we can unit test a servlet that makes calls to
* <code>getServletConfig()</code>, <code>getServletContext()</code>,
* <code>log()</code>, ... (i.e. methods inherited from
* <code>GenericServlet</code>).
*
* @see TestSampleServletConfig_Helper
*/
public void testServletConfig() throws ServletException
{
SampleServletConfig servlet = new SampleServletConfig();
// VERY IMPORTANT : Call the init() method in order to initialize the
// Servlet ServletConfig object.
servlet.init(config);
assertEquals("value1 used for testing", servlet.getConfigData());
}