Download
2) decompression Cactus, put under lib add the following jar to the eclipse's classpath:
cactus.core.framework.uberjar.javaEE.14-1.8.1.jar
commons-httpclient-3.1.jar
commons-logging-1.1.jar
aspectjrt-1.5.3.jar
servlet-api-2.4.jar
org.mortbay.jetty-5.1.9.jar
3) to be test-class
/* 待测试类SimpleServlet.java */
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class SampleServlet extends HttpServlet {
private static final long serialVersionUID = -4934598964259783805L;
public boolean isAuthenticated(HttpServletRequest request){
HttpSession session = request.getSession(false);
if (session == null){
return false;
}
String authenticationAttribute =
(String) session.getAttribute("authenticated");
return Boolean.valueOf(authenticationAttribute).booleanValue();
}
}
4) Preparation of test-class
import org.apache.cactus.ServletTestCase;
import org.apache.cactus.WebRequest;
public class TestSampleServletIntegration extends ServletTestCase{
private SampleServlet servlet;
@Override
protected void setUp(){
servlet = new SampleServlet();
}
public void testIsAuthenticated(){
session.setAttribute("authenticated", "true");
assertTrue(servlet.isAuthenticated(request));
}
public void testIsNotAuthenticate(){
assertFalse(servlet.isAuthenticated(request));
}
public void beginIsAuthenticateNoSession(WebRequest request){
request.setAutomaticSession(false);
}
public void testISAuthenticatedNoSession(){
assertFalse(servlet.isAuthenticated(request));
}
}
import org.apache.cactus.extension.jetty.Jetty5xTestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class TestAllWithJetty extends TestCase {
public static Test suite(){
System.setProperty("cactus.contextURL", "http://localhost:8080/test");
TestSuite suite = new TestSuite("all test with Jetty");
suite.addTestSuite(TestSampleServletIntegration.class);
return new Jetty5xTestSetup(suite);
}
} At the next eclipse to Junit run TestAllWithJetty.java, ok to see the Green article ~ ~
Note the main points:
1.commons-httpclient package dependent on commons-code.jar, otherwise the run-time will be thrown:
java.lang.NoClassDefFoundError: org / apache / commons / codec / DecoderException
Jetty Integration 2.Cactus and when testing at TestAllWithJetty category, return the test case should be Jetty5xTestSetup, if the running back will appear Jetty6xTestSetup category can not find the error, import the Jetty package if using the latest jetty-6.1.15.jar , run-time error will also appear with Cactus lib own org.mortbay.jetty-5.1.9.jar, seems Cactus current version does not support Jetty6
PS: an example from <Junit in action> Chapter 8







