转自:http://caterpillar.onlyfun.net/GossipCN/JUnit/FirstCactusWithTomcat.htm
来看看如何使用Cactus配合Tomcat来运行一个简单的Servlet测试,我们先取得Cactus相关档案,请至 Cactus 官方网站 下载,下载后解开压缩档案,将其下lib目录中的commons-logging-xxx.jar、aspectjrt-xxx.jar、cactus- xxx.jar、commons-httpclient-xxx.jar与junit-xxx.jar放置在您的Web应用程式的WEB-INF/lib 目录下。
您将使用Cactus的ServletTestRedirector作为之前介绍的Redirector Proxy,并使用Cactus的ServletTestRunner作为执行测试时的TestRunner,这两个被撰写为Servlet,所以您在 web.xml中加以定义:
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <description> Cactus Demo </description> <display-name>Cactus Demo</display-name> <servlet> <servlet-name>ServletRedirector</servlet-name> <servlet-class> org.apache.cactus.server.ServletTestRedirector </servlet-class> </servlet> <servlet> <servlet-name>ServletTestRunner</servlet-name> <servlet-class> org.apache.cactus.server.runner.ServletTestRunner </servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletRedirector</servlet-name> <url-pattern>/ServletRedirector</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletTestRunner</servlet-name> <url-pattern>/ServletTestRunner</url-pattern> </servlet-mapping> </web-app>
package onlyfun.caterpillar.test; import org.apache.cactus.ServletTestCase; import org.apache.cactus.WebRequest; import onlyfun.caterpillar.LoginServlet; public class LoginServletTest extends ServletTestCase { public void beginValidUser(WebRequest webRequest) { webRequest.addParameter("username", "justin"); webRequest.addParameter("password", "123456"); } public void testValidUser() { LoginServlet loginServlet = new LoginServlet(); assertTrue(loginServlet.isValidUser(request)); } public void beginInValidUser(WebRequest webRequest) { webRequest.addParameter("username", "guest"); webRequest.addParameter("password", "123456"); } public void testInValidUser() { LoginServlet loginServlet = new LoginServlet(); assertFalse(loginServlet.isValidUser(request)); } }
package onlyfun.caterpillar; import javax.servlet.http.*; public class LoginServlet extends HttpServlet { public boolean isValidUser(HttpServletRequest request) { String username = request.getParameter("username"); String password = request.getParameter("password"); if(username == null || password == null || !username.equals("justin") || !password.equals("123456")) { return false; } else { return true; } } }
... <servlet> <servlet-name>ServletTestRunner</servlet-name> <servlet-class> org.apache.cactus.server.runner.ServletTestRunner </servlet-class> <init-param> <param-name>xsl-stylesheet</param-name> <param-value>styles/cactus-report.xsl</param-value> </init-param> </servlet> ...