Posted on 2007-11-02 12:44
G_G 阅读(1004)
评论(0) 编辑 收藏 所属分类:
JUnit
学习测试留个印
测试 Servlet 使用:
package
jetty.test.supper;
import
java.io.File;
import
javax.servlet.http.HttpServletRequest;
import
jetty.LoginServlet;
import
com.meterware.httpunit.GetMethodWebRequest;
import
com.meterware.httpunit.WebConversation;
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.TestCase;
public
class
HttpUnitTest
extends
TestCase {
public
void
ctestUrl()
throws
Exception{
System.out.println(
"
直接获取网页内容:
"
);
WebConversation wc
=
new
WebConversation();
WebResponse wr
=
wc.getResponse(
"
http://www.google.com
"
);
System.out.println( wr.getText() );
}
public
void
testRun1()
throws
Exception{
System.out.println(
"
无参数测试:
"
);
//
建立服务器
ServletRunner sr
=
new
ServletRunner(
new
File(
"
WebRoot\\WEB-INF\\test.xml
"
));
//
模拟客户端
ServletUnitClient sc
=
sr.newClient();
//
URL 定位
WebRequest request
=
new
GetMethodWebRequest(
"
http://localhost:7000/cactusDemo
"
);
WebResponse response
=
sc.getResponse( request );
//
运行
System.out.println(response.getText()
+
"
\n
"
);
}
public
void
testRun2()
throws
Exception{
System.out.println(
"
Session 和 request 测试:
"
);
ServletRunner sr
=
new
ServletRunner(
new
File(
"
WebRoot\\WEB-INF\\test.xml
"
));
ServletUnitClient sc
=
sr.newClient();
WebRequest request
=
new
GetMethodWebRequest(
"
http://localhost/cactusDemo
"
);
//
Parameter 加参 use
request.setParameter(
"
use
"
,
"
web
"
);
//
取出 Servlet : LoginServlet 方法准备执行
InvocationContext ic
=
sc.newInvocation( request );
LoginServlet se
=
(LoginServlet)ic.getServlet();
HttpServletRequest re
=
ic.getRequest() ;
//
request session 加参 use
re.setAttribute(
"
use
"
,
"
re
"
);
re.getSession(
true
).setAttribute(
"
use
"
,
"
re
"
);
se.doGet(re,ic.getResponse());
//
关键:运行测试方法
//
获取 out
WebResponse response
=
ic.getServletResponse();
System.out.println(response.getText());
}
}
test.xml
<?
xml version="1.0" encoding="UTF-8"
?>
<
web-app
xmlns
="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
version
="2.4"
xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>
<
servlet
>
<
servlet-name
>
cactusDemo
</
servlet-name
>
<
servlet-class
>
jetty.LoginServlet
</
servlet-class
>
</
servlet
>
<
servlet-mapping
>
<
servlet-name
>
cactusDemo
</
servlet-name
>
<
url-pattern
>
/cactusDemo
</
url-pattern
>
</
servlet-mapping
>
</
web-app
>
测试 JSP:
Cookbook
参考
不使用容器 进行 测试 jsp
测试Struts:
StrutsTestCase
参考