论坛首页 综合技术论坛

在eclipse中用jetty和cactus为servlet做单元测试

浏览 3553 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-09-24  
1. 下载jetty,解压到安装目录并在eclipse中做好配置。
2. 下载cactus,将lib目录下的aspectjrt-1.5.3.jar, cactus.core.framework.uberjar.javaEE.14-1.8.0.jar, commons-httpclient-3.1.jar,commons-logging-1.1.jar,httpunit-1.6.jar,junit-3.8.2.jar解压到jetty的lib目录下。
3. 修改myapp的WEB-INF目录下的web.xml文件,添加如下内容:
<servlet>
  	<servlet-name>ServletRedirector</servlet-name>
  	<servlet-class>org.apache.cactus.server.ServletTestRedirector</servlet-class>
  	<init-param>
    	<param-name>param1</param-name>
    	<param-value>value1 used for testing</param-value>
  	</init-param>
	</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>

4. 建立测试的Java文件,TestMyServlet.java
public class TestMyServlet extends ServletTestCase {
	
	public TestMyServlet(String theName) throws Exception
    {
        super(theName);
        
        System.setProperty("cactus.contextURL", "http://localhost:8080/myapp");
    }

    public static Test suite()
    {
    	TestSuite suite = new TestSuite();        
    	suite.addTestSuite(TestMyServlet.class);
        return new Jetty6xTestSetup(suite);
    }

    public void testMyServletInitialized()
    {
    	MyServlet servlet = new MyServlet();
    	try {
			servlet.init(config);
		} catch (ServletException e) {
			e.printStackTrace();
		}
        assertTrue(servlet.getInitialized());
    }

5. 建立待测试的Java文件,MyServlet.java
public class MyServletextends HttpServlet {

	protected static boolean initialized = false;

	public void init(ServletConfig servletConfig) throws ServletException
	{
		super.init(servletConfig);
		
		if (MyServlet.initialized)
			return;
		
		MyServlet.initialized = true;
	}
	
	public boolean getInitialized() {
		return MyServlet.initialized;
	}
}


6. 启动jetty,用junit运行测试,呵呵,绿了。
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics