[Cactus入门]eclipse环境下,用Cactus和Jetty集成来测试Servlet

1)下载[url=http://jakarta.apache.org/site/downloads/downloads_cactus.cgi]Cactus-1.8.1[/url]
下载[url=http://commons.apache.org/downloads/download_codec.cgi]commons-codec-1.3[/url]

2)解压Cactus,把lib下的以下jar加入到eclipse的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)待测试类
/* 待测试类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)编写测试类
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);
}

}


在eclipse下,以Junit方式运行 TestAllWithJetty.java ,ok看到绿条~~

注意要点:
1.commons-httpclient包依赖commons-code.jar,否则运行时会抛出异常:
java.lang.NoClassDefFoundError: org/apache/commons/codec/DecoderException
2.Cactus和Jetty集成时,在TestAllWithJetty测试类,返回的test case应该是Jetty5xTestSetup,若返回Jetty6xTestSetup运行会出现找不到类的错误, 导入的Jetty包若用最新的jetty-6.1.15.jar,运行时也会出现错误,用Cactus lib自带的org.mortbay.jetty-5.1.9.jar,看来目前的Cactus版本不支持Jetty6
PS:例子来自<Junit in action>的第8章
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值