EasyMock测试Servlet端实例
下面介绍两个类Login 和 LoginTest,其中LoginTest是用EasyMock对Login的servlet的测试类
Login.java
package servlet.manage.users;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import delegate.common.message.MessInfo;
import delegate.logic.manage.users.MLogin;
/**
* @Project Name : Login
*
* @author Zou Shasha
*
* This class is a servlet client for user login by which the UserID and password are verified.
**/
@SuppressWarnings("serial")
public class Login extends HttpServlet {
/**
* Constructor of the object.
*/
public Login() {
super();
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Gets a RequestDispatcher object and forwards a request from a servlet to "menu.jsp" on the server.
request.getRequestDispatcher("menu.jsp").forward(request, response);
//response.sendRedirect("menu.jsp");
}
/**
* The doPost method of the servlet. <br>
* This method is called when a form has its tag value method equals to post.
* And gets the values of User ID and password and veri
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Sets the content type of the response for text or html being sent to the client
response.setContentType("text/html;charset=utf-8");
//Overrides UTF-8 used in the body of this request.
request.setCharacterEncoding("utf-8");
//Returns a PrintWriter object that can send character text to the client.
PrintWriter out = response.getWriter();
//Returns the value of UserID as a String
String UserID = request.getParameter("UserID");
//Returns the value of Password as a String
String Password = request.getParameter("Password");
//Create a new instance of MLogin class
MLogin oper = new MLogin();
//Verifies the User ID and the password and returns the result as a String
String identify = oper.loginCheck(UserID, Password);
//The User ID and the password are legal
if (identify.equals("true")) {
//Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
HttpSession session = request.getSession(true);
//Binds the value of UserID and Password to this session, using UserID and Password String.
session.setAttribute("UserID", UserID);
session.setAttribute("Password", Password);
//Goes to the menu page.
out.println("<script>");
out.println("window.location.href='../menu/home'");
out.println("</script>");
} else if (identify.equals("UserIDError")) {
//Pops up alarm in case of non-registered user ID and goes to the login page.
String message1 = new String(new MessInfo().getMessInfo("user_login_5").getBytes("iso-8859-1"), "UTF-8");
out.println("<script>");
out.println("alert('" + message1 + "')");
out.println("</script>");
out.println("<script>");
out.println("window.location.href='../../../Login.jsp'");
out.println("</script>");
} else if (identify.equals("PasswordError")) {
//Pops up alarm in case of invalid password and goes to the login page.
String message2 = new String(new MessInfo().getMessInfo("user_login_6").getBytes("iso-8859-1"), "UTF-8");
out.println("<script>");
out.println("alert('" + message2 + "')" );
out.println("</script>");
out.println("<script>");
out.println("window.location.href='../../../Login.jsp'");
out.println("</script>");
} else {
//Pops up alarm in case of database access failure and goes to the login page.
String message3 = new String(new MessInfo().getMessInfo("user_login_7").getBytes("iso-8859-1"), "UTF-8");
out.println("<script>");
out.println("alert('" + message3 + "')");
out.println("</script>");
out.println("<script>");
out.println("window.location.href='../../../Login.jsp'");
out.println("</script>");
}
}
}
LoginTest.java
package servlet.manage.users;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.easymock.EasyMock;
import delegate.common.message.MessInfo;
/**
* @Project Name : LoginTest
* @author Liu Chen
* Zou Shasha
*
* This class is the test class for the Login class.
*
*/
public class LoginTest {
private Login servlet;
private HttpServletRequest mockRequest;
private HttpServletResponse mockResponse;
public LoginTest() {
}
@Before
public void setUp() {
servlet = new Login();
//创建request和response的Mock
mockRequest = (HttpServletRequest)EasyMock.createMock(HttpServletRequest.class);
mockResponse = (HttpServletResponse) EasyMock.createMock(HttpServletResponse.class);
}
@After
public void tearDown() {
}
@Test
public void testDoGetHttpServletRequestHttpServletResponse() throws ServletException, IOException {
RequestDispatcher dispatcher = (RequestDispatcher) EasyMock.createMock(RequestDispatcher.class);
EasyMock.expect(mockRequest.getRequestDispatcher("menu.jsp")).andReturn(dispatcher);
dispatcher.forward(mockRequest, mockResponse);
//回放
EasyMock.replay(mockRequest);
EasyMock.replay(mockResponse);
EasyMock.replay(dispatcher);
servlet.doGet(mockRequest, mockResponse);
EasyMock.verify(mockRequest);
EasyMock.verify(mockResponse);
EasyMock.verify(dispatcher);
}
@Test
public void testLoginSuccess() throws IOException {
//Sets the content type of the response for text or html being sent to the client
mockResponse.setContentType("text/html;charset=utf-8");
//Overrides UTF-8 used in the body of this request.
mockRequest.setCharacterEncoding("utf-8");
//录制request和response的动作
EasyMock.expect(mockRequest.getParameter("UserID")).andReturn("123");
EasyMock.expect(mockRequest.getParameter("Password")).andReturn("123");
StringWriter output = new StringWriter();
PrintWriter contentWriter = new PrintWriter(output);
EasyMock.expect(mockResponse.getWriter()).andReturn(contentWriter);
HttpSession session = (HttpSession) EasyMock.createMock(HttpSession.class);
EasyMock.expect(mockRequest.getSession(true)).andReturn(session);
session.setAttribute("UserID", "123");
session.setAttribute("Password","123");
//回放
EasyMock.replay(session);
EasyMock.replay(mockRequest);
EasyMock.replay(mockResponse);
//开始测试Servlet的doPost方法
try {
servlet.doPost(mockRequest, mockResponse);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EasyMock.verify(session);
EasyMock.verify(mockRequest);
EasyMock.verify(mockResponse);
// System.out.println(output.toString());
assertEquals("<script>\r\nwindow.location.href='../menu/home'\r\n</script>\r\n", output.toString());
}
@Test
public void testLoginUserIDError() throws IOException {
//Sets the content type of the response for text or html being sent to the client
mockResponse.setContentType("text/html;charset=utf-8");
//Overrides UTF-8 used in the body of this request.
mockRequest.setCharacterEncoding("utf-8");
//录制request和response的动作
// mockRequest.getParameter("UserID");
// EasyMock.expectLastCall().andReturn("123");//设置前一方法被调用时的返回值
EasyMock.expect(mockRequest.getParameter("UserID")).andReturn("aaa");
EasyMock.expect(mockRequest.getParameter("Password")).andReturn("123");
StringWriter output = new StringWriter();
PrintWriter contentWriter = new PrintWriter(output);
EasyMock.expect(mockResponse.getWriter()).andReturn(contentWriter);
//回放
EasyMock.replay(mockRequest);
EasyMock.replay(mockResponse);
try {
servlet.doPost(mockRequest, mockResponse);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EasyMock.verify(mockRequest);
EasyMock.verify(mockResponse);
// System.out.println(output.toString());
String message = new String(new MessInfo().getMessInfo("user_login_5").getBytes("iso-8859-1"), "UTF-8");
assertEquals("<script>\r\nalert('"+message+"')\r\n</script>\r\n<script>\r\nwindow.location.href='../../../Login.jsp'\r\n</script>\r\n", output.toString());
}
@Test
public void testLoginPwdError() throws IOException {
//Sets the content type of the response for text or html being sent to the client
mockResponse.setContentType("text/html;charset=utf-8");
//Overrides UTF-8 used in the body of this request.
mockRequest.setCharacterEncoding("utf-8");
//录制request和response的动作
// mockRequest.getParameter("UserID");
// EasyMock.expectLastCall().andReturn("123");//设置前一方法被调用时的返回值
EasyMock.expect(mockRequest.getParameter("UserID")).andReturn("123");
EasyMock.expect(mockRequest.getParameter("Password")).andReturn("aaa");
StringWriter output = new StringWriter();
PrintWriter contentWriter = new PrintWriter(output);
EasyMock.expect(mockResponse.getWriter()).andReturn(contentWriter);
//回放
EasyMock.replay(mockRequest);
EasyMock.replay(mockResponse);
try {
servlet.doPost(mockRequest, mockResponse);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EasyMock.verify(mockRequest);
EasyMock.verify(mockResponse);
String message = new String(new MessInfo().getMessInfo("user_login_6").getBytes("iso-8859-1"), "UTF-8");
assertEquals("<script>\r\nalert('"+message+"')\r\n</script>\r\n<script>\r\nwindow.location.href='../../../Login.jsp'\r\n</script>\r\n", output.toString());
}
}
另外,大多数人在写源程序的时候都有用到request.setAttribute("list",list);其中list表示业务逻辑的运行后的封装结果,这个在EasyMock中可用mockRequest.setAttribute(EasyMock.eq("list"), (List)EasyMock.anyObject())
或者mockRequest.setAttribute(EasyMock.eq("list"), EasyMock.isA(List.class)) 模拟。
分享到:
相关推荐
`junit`和`easymock`是两个非常重要的Java测试工具,它们可以帮助我们有效地对Servlet进行单元测试和模拟测试。 `junit`是一个流行的开源单元测试框架,它为Java程序员提供了一种方便的方式来编写和运行可重复的...
依赖注入允许开发者将应用程序的组件设计为POJO,这意味着这些POJO能够在不依赖Spring容器或其他框架的情况下,通过简单的new操作符进行实例化和测试。这一特性极大地提高了单元测试的便利性和代码的可测试性。 ...
- Spring TestContext框架支持模拟对象(如Mockito)和存根(如EasyMock),使得在测试中可以替换真实的依赖,从而隔离测试。 - 使用`@Autowired`和`@Qualifier`注解可以自动注入测试所需的bean,同时可以通过`@...
它提供了一种简单的方法来为GWT客户端代码编写快速的Java测试,而无需GWTTestCase或任何servlet容器实例! 这意味着您可以不受限制地使用任何Java工具:JUnit,反射,Easymock,Mockito等。 编写测试如下所示: @...
6. **Wrapper(包装器)**: 为每个Servlet创建一个Wrapper对象,封装Servlet实例并处理请求。 7. **Servlet**: 最后,Wrapper调用Servlet的`service()`方法来处理请求,Servlet执行实际的业务逻辑。 8. **Response**...
7. **测试**:在Spring2中,我们可以使用JUnit进行单元测试,结合`Mockito`或`EasyMock`进行依赖模拟,确保代码质量。 以上就是MyEclipse中配置Spring2的基本流程和相关知识点。虽然Spring已经发展到更高版本,但...
ant awt easymock ejb guava hibernate ibatis jackson jsaperreprts java.io java.lang mail java.math java.util xml java java实例 javafx jdbc jfreechart jmeter jogl jpa log4j lucene maven mybatis poi ...