Posted on 2007-10-31 11:11
G_G 阅读(1079)
评论(2) 编辑 收藏 所属分类:
JUnit
1. HttpUnit
1>servlet可以脱离容器,容易把该测试写入ant或maven脚本,让测试进行。
2>httpunit在测试servlet行为时,采用的是完全模拟浏览器,有时测试比较难写。
package Cactus.test.support;
import junit.framework.TestCase;
import Cactus.HelloWorld;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.servletunit.InvocationContext;
import com.meterware.servletunit.ServletRunner;
import com.meterware.servletunit.ServletUnitClient;
import junit.framework.Assert;
public class HttpUnitTestHelloWorld extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testHelloWorld() {
try {
// 创建Servlet的运行环境
ServletRunner sr = new ServletRunner();
// 向环境中注册Servlet
sr.registerServlet("HelloWorld", HelloWorld.class.getName());
// 创建访问Servlet的客户端
ServletUnitClient sc = sr.newClient();
// 发送请求
WebRequest request = new GetMethodWebRequest("http://localhost/HelloWorld");
request.setParameter("username", "testuser");
//用委托加载 is
InvocationContext ic = sc.newInvocation(request);
HelloWorld is = (HelloWorld) ic.getServlet();
// 测试servlet的某个方法
Assert.assertTrue(is.authenticate());
// 获得模拟服务器的信息
WebResponse response = sc.getResponse(request);
// 断言
Assert.assertTrue(response.getText().equals("testuser:Hello World!"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Jetty
package Cactus.test.support;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.servlet.ServletHandler;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebResponse;
import junit.framework.Assert;
import junit.framework.TestCase;
public class JettySampleTest extends TestCase {
Server server;
protected void setUp() throws Exception {
//通过代码设置并启动一个服务器,该服务器是servlet的测试容器
super.setUp();
server = new Server();
Connector connector=new SocketConnector();
connector.setPort(80);
server.setConnectors(new Connector[]{connector});
ServletHandler handler=new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping("Cactus.HelloWorld", "/");
server.start();
}
protected void tearDown() throws Exception {
super.tearDown();
server.stop();
}
public void testHellWorld() {
try {
WebConversation wc = new WebConversation();
WebResponse web = wc.getResponse("http://127.0.0.1/HelloWorld");
String result=web.getText();
Assert.assertEquals(result,"null:Hello World!");
} catch (Exception e) {
e.printStackTrace();
}
}
}