`
ZOODragon
  • 浏览: 68704 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

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

 

分享到:
评论

相关推荐

    easymock测试servlet

    在"easymock测试servlet"的场景中,我们看到`SampleServletTest`类正在使用Easymock来测试`SampleServlet`类的行为。以下是一些关键知识点: 1. **Easymock库**:Easymock是一个开源库,它提供了模拟Java对象的方法...

    4-EasyMock-Servlet.rar

    在“4-EasyMock-Servlet.rar”这个压缩包中,我们很可能是得到了一个关于如何使用EasyMock进行Servlet测试的教程或者示例代码。让我们详细探讨一下EasyMock与Servlet结合使用的相关知识点。 1. **EasyMock基本概念*...

    easymock资料和源代码实例

    下面我们将详细探讨Easymock的基本概念、工作原理以及如何通过源代码实例进行应用。 **Easymock基本概念** 1. **模拟对象(Mock Objects)**:在单元测试中,模拟对象是代替真实对象的替代品,它们根据预设的行为...

    转:EasyMock 单元测试

    EasyMock 是一个流行的 Java 单元测试框架,它帮助开发者创建模拟对象来测试目标类的行为。这篇文档将深入探讨 EasyMock 的使用方法和原理,以便更好地理解和应用这一工具。 首先,让我们理解 EasyMock 的核心概念...

    easymock-request.getParamsNames

    本文将详细讲解如何使用 Easymock 对 Servlet 进行单元测试,特别是针对 `HttpServletRequest` 中获取参数的方法 `getParamsNames()`。 在Servlet编程中,`HttpServletRequest` 是一个核心接口,它提供了处理HTTP...

    EasyMock单元测试例子

    这个"EasyMock单元测试例子"提供了几个示例,帮助我们更好地理解和应用EasyMock。 EasyMock的基本概念: 1. **模拟对象(Mock Object)**:在单元测试中,我们可能不希望依赖实际的外部服务或数据库。模拟对象可以...

    Junit+EasyMock单元测试使用资料以及案例分析

    3. **创建并配置测试用例**:在`@Test`注解的测试方法中,注入模拟的`UserRepository`到`UserService`实例。 4. **执行测试**:调用`UserService`的方法,如`getUserProfile()`,该方法内部会调用`UserRepository`。...

    EasyMock 实例

    EasyMock 是一个强大的Java模拟框架,它允许开发者在单元测试中创建和控制对象的行为,以模拟复杂的系统交互。这个框架的使用可以极大地提高测试的效率和覆盖率,因为它使得测试代码可以独立于实际的依赖进行执行。 ...

    EasyMock

    这个框架的出现,极大地简化了对那些难以或无法直接实例化的类的测试,比如接口或者静态方法。EasyMock的核心理念是通过预定义对象的预期行为来隔离被测试代码,从而实现对系统组件的精确测试。 在源码层面,...

    模拟测试辅助工具easyMock.zip

    EasyMock 是一套通过简单的方法对于指定的接口或类生成 Mock 对象的类库,它能利用对接口或类的模拟来辅助单元测试。 Mock 方法是单元测试中常见的一种技术,它的主要作用是模拟一些在应用中不容易构造或者比较...

    servlet测试jar包

    `junit`和`easymock`是两个非常重要的Java测试工具,它们可以帮助我们有效地对Servlet进行单元测试和模拟测试。 `junit`是一个流行的开源单元测试框架,它为Java程序员提供了一种方便的方式来编写和运行可重复的...

    EasyMock.jar

    7. **静态方法模拟**:虽然EasyMock主要针对实例方法的模拟,但它也提供扩展机制(如使用EasyMock Class Extension)来模拟静态方法。 8. **类型安全**:EasyMock 2.5.1版可能已经提供了类型安全的API,这使得在...

    EasyMock 简介

    EasyMock 是一套用于通过简单的方法对于给定的接口生成 Mock 对象的类库,旨在解决单元测试中的 Mock 对象构建问题。以下是 EasyMock 的详细介绍: 单元测试与 Mock 方法 单元测试是对应用中的某一个模块的功能...

    easyMock

    EasyMock 是一个强大的Java模拟框架,它允许开发者在单元测试中创建和控制对象的行为,以模拟复杂的依赖关系。这个框架的出现使得测试更加简洁、独立,可以有效地验证代码的正确性,而无需运行实际的依赖服务或库。...

    EasyMock介绍和使用

    EasyMock是一款强大的Java模拟框架,它允许开发者在进行单元测试时创建和控制对象的行为。这个工具使得测试更加独立,可以隔离被测试代码与其他依赖的系统,从而提高测试的效率和质量。EasyMock的核心理念是通过模拟...

    easymock.jar,easymockclassextension.jar

    Easymock是一个流行的Java单元测试框架,它允许开发者创建模拟对象来测试代码。这个框架使得测试更加简单,因为你可以模拟任何复杂的交互和行为,而无需实际运行依赖的组件。在给定的压缩包文件中,包含两个核心的...

    easymock-2.5.2工具 下载

    EasyMock 是一个强大的开源工具,专门用于生成模拟对象(Mock Objects),在软件开发特别是单元测试领域,它扮演着至关重要的角色。这个工具的版本为2.5.2,提供了对Java编程语言的支持,使得开发者能够方便地创建和...

    easymock-3.2.zip

    EasyMock 3.2 是一个流行的开源Java模拟框架,它为开发者提供了强大的单元测试支持。在Java开发中,单元测试是验证代码独立模块正确性的关键步骤。EasyMock可以帮助程序员模拟对象的行为,使得测试过程更加可控,...

Global site tag (gtag.js) - Google Analytics