Java Reference
In-Depth Information
Listing 14.2
Using Cactus to unit test SampleServlet
[...]
import org.apache.cactus.ServletTestCase;
import org.apache.cactus.WebRequest;
public class TestSampleServletIntegration extends ServletTestCase {
private SampleServlet servlet;
protected void setUp() {
servlet = new SampleServlet();
}
public void testIsAuthenticatedAuthenticated() {
session.setAttribute("authenticated", "true");
assertTrue(servlet.isAuthenticated(request));
}
B
public void testIsAuthenticatedNotAuthenticated() {
assertFalse(servlet.isAuthenticated(request));
}
public void beginIsAuthenticatedNoSession(WebRequest request) {
request.setAutomaticSession(false);
}
C
public void testIsAuthenticatedNoSession() {
assertFalse(servlet.isAuthenticated(request));
}
}
Now you're probably asking, ”At what place do the session B and request C objects
get declared and initialized?” The answer is straightforward—they come from the base
class, ServletTestCase , which is part of the Cactus API .
As you can see, the Cactus test case meets all of our requirements. It gives us access
to the container objects, inside our JU nit test cases. As you can see from the previous
listing, writing a Cactus test case involves several key points:
The Cactus test case must extend one of the following, depending on what type
of component you're testing: ServletTestCase , JSPTestCase , or FilterTest-
Case . This is a rule: because Cactus extends the 3.8.x version of JU nit, your test
cases always have to extend one of the latter classes.
The Cactus framework exposes the container objects (in this case the Http-
ServletRequest and HttpSession objects) to your tests, making it easy and
quick to write unit tests.
You get a chance to implement two new methods: begin XXX and end XXX . These two
new methods are executed on the client side, and you can use them to place cer-
tain values in the request object or to get certain values from the response object.
In order for Cactus to expose the container objects, Cactus needs to get them from
the JVM they live in, and because the container is the only one managing the life-
cycle of these objects, Cactus tests need to interact directly with the container. This
leads us to the conclusion that Cactus tests must be deployed inside the container.
 
 
 
 
Search WWH ::




Custom Search