package com.jadyer.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import junit.framework.Assert;
import org.apache.cactus.ServletTestCase;
import org.apache.cactus.WebRequest;
import org.xml.sax.SAXException;
import com.meterware.httpunit.WebResponse;
/**
* ----------------------------------------------------------------------------------------------------
* 本类是一个继承了org.apache.cactus.ServletTestCase的类(它内部间接继承了junit.framework.TestCase)
* 这样此类便自动拥有了ServletAPI引用,比如要使用HttpSession就可以直接session.setAttribute()
* ----------------------------------------------------------------------------------------------------
* 它所依赖的基础jar,如下所示
* aspectjrt-1.5.3.jar
* cactus.core.framework.uberjar.javaEE.14-1.8.1.jar
* cactus.integration.ant-1.8.1.jar
* cactus.integration.shared.api-1.8.1.jar
* commons-codec-1.6.jar(需单独下载)
* commons-discovery-0.4.jar
* commons-httpclient-3.1.jar
* commons-logging-1.1.jar
* geronimo-j2ee-management_1.0_spec-1.1.jar
* httpunit-1.6.jar
* Tidy.jar或者nekoHTML.jar和xercesMinimal.jar(本例中的endDoGet()方法要用到)
* ----------------------------------------------------------------------------------------------------
* Tidy.jar需要单独下载
* nekoHTML.jar和xercesMinimal.jar均可从下载到的nekohtml-1.9.18.zip找到
* nekoHTML的下载地址为http://sourceforge.net/projects/nekohtml/files/
* ----------------------------------------------------------------------------------------------------
* Created by 玄玉 on 2013/07/11 10:49.
*/
public class LoginServletTest extends ServletTestCase {
private LoginServlet loginServlet;
//它是在ServerSide执行的
public void setUp(){
loginServlet = new LoginServlet();
}
//beginXxx()方法是在ClientSide执行的
//若想在testLogin()中获取到这里request添加的username参数,则该方法就应命名为beginLogin()
public void beginLogin(WebRequest request){
request.addParameter("username", "Jadyer");
}
//它是在ServerSide执行的
public void testLogin(){
//获取GET参数
Assert.assertEquals(request.getParameter("username"), "jadyer");
//登录失败
//session.setAttribute("loginUser", "玄玉");
Assert.assertFalse(loginServlet.login(request));
//登录成功
session.setAttribute("loginUser", "https://jadyer.cn/");
Assert.assertTrue(loginServlet.login(request));
}
//它是在ServerSide执行的
public void testDoGet() throws ServletException, IOException {
loginServlet.doGet(request, response);
}
//endXxx()方法是在ClientSide执行的,该方法对应testDoGet()
public void endDoGet(WebResponse resp) throws SAXException {
//这里使用com.meterware.httpunit.WebResponse,而非org.apache.cactus.WebResponse
//前者提供了很多增强功能(它要额外借助Tidy.jar或者nekoHTML.jar和xercesMinimal.jar作为辅助包)
Assert.assertEquals(resp.getTables()[0].getCellAsText(0,0), "username");
Assert.assertEquals(resp.getTables()[0].getCellAsText(0,1), "password");
}
}