写了个Servlet的测试用例,初学单元测试,大家帮我看看。

用的JUnit是4.4版,EasyMock2.3。

这是Servlet:
package net.javayuan.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @(#)LoginServlet.java 2008-6-4 下午11:39:05
*
* @author Yuan
* LoginServlet
*/
public class LoginServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = -7068817837964223972L;

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException{
String username = request.getParameter("username").trim();
String password = request.getParameter("password");
if ("yuan".equals(username) && "123456".equals(password))
response.sendRedirect("welcome.jsp");
else
response.sendRedirect("error.jsp");
}
}


这是Test Case:
package net.javayuan.servlet;

import static org.easymock.EasyMock.*;

import java.io.IOException;

import org.junit.Test;
import org.junit.After;
import org.junit.Before;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @(#)LoginServlet.java 2008-6-5 上午09:19:42
*
* @author Yuan
* LoginServlet Test Case
*/
public class LoginServletTest {

private LoginServlet servlet;
private HttpServletRequest mockRequest;
private HttpServletResponse mockResponse;

@Before
public void setUp(){

servlet = new LoginServlet();

//创建request和response的Mock
mockRequest = createMock(HttpServletRequest.class);
mockResponse = createMock(HttpServletResponse.class);
}

@After
public void tearDown(){

//为了验证指定的调用行为确实发生了,要调用verify(mock)进行验证。
verify(mockRequest);
verify(mockResponse);
}

/**
* 测试doPost方法
* @throws IOException
* @throws ServletException
* */
@Test
public void testDoPost() throws IOException, ServletException{

//录制request和response的动作
mockRequest.getParameter("username");
expectLastCall().andReturn("yuan");//设置前一方法被调用时的返回值

mockRequest.getParameter("password");
expectLastCall().andReturn("123456");

mockResponse.sendRedirect("welcome.jsp");

//回放
replay(mockRequest);
replay(mockResponse);

//开始测试Servlet的doPost方法
servlet.doPost(mockRequest, mockResponse);
}

}


不知道测试重定向的页面是不是这么测,我想应该是的。
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页