EasyMock测试Servlet端实例

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)) 模拟。

 

你可能感兴趣的:(html,jsp,servlet,JUnit,UP)