如何使用 junit 和 jmock 对 MVC Model 2 应用程序进行单元测试?

发布于 2024-11-30 16:32:23 字数 2477 浏览 6 评论 0原文

如何使用 junit 和 jmock 对 MVC Model 2 应用程序进行单元测试?

我有一个功能齐全的 MVC Model 2 应用程序,但单元测试为零。我正在围绕应用程序实施单元测试。我想对我的控制器 servlet 方法进行单元测试。控制器 servlet 调用 dao 类来执行 CRUD 操作。示例:向用户显示一个登录对话框,用户输入 userid/pwd 并单击“提交”按钮。该请求由控制器的 processRequest() 和 validateLogin() 方法处理,然后通过 DAO 类查询数据库,最后如果登录成功,则返回 LoginBean 和数据。

我的问题是如何对这种代码进行单元测试?

下面提供了示例代码,以便更好地理解该问题。

---- ControllerServlet.java ----

public class ControllerServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

public void processRequest(HttpServletRequest request, HttpServletResponse response, String opcode) throws ServletException, IOException {
    String url = "index.jsp"; //default url
    HttpSession session = request.getSession();
    try {
        if (opcode.equalsIgnoreCase("authenticate")) {
            String firstName = GenericUtils.getParameter(request, "firstName");
            String lastName = GenericUtils.getParameter(request, "lastName");
            List userLst = validateLogin(firstName, lastName, request);
            boolean loginValid = CollectionUtils.isNotEmpty(userLst);
            request.setAttribute("loginValid", String.valueOf(loginValid)); //setting value in request attribute

            //if login is valid set the LoginBean in session
            if (loginValid) {
                LoginBean loginBean = (LoginBean) userLst.get(0);
                session.setAttribute("loginBean", loginBean);
                getAllProducts(request);
                url = "listProducts.jsp";
            } else {
                url = "login.jsp";
            }
        } 
}
catch.....
//some more code here
} 

public List validateLogin(String firstName, String lastName, HttpServletRequest request) throws ServletException, IOException {
    List userLst = new ArrayList();
    if (firstName.length() > 0 && lastName.length() > 0) {
        userLst = MasterDao.checkLoginValid(firstName, lastName);//DAO call goes here
    }
    return userLst;
}

}

我如何对这种东西进行单元测试?我尝试使用 junit 和 jmock 创建单元测试,但我不确定如何使用 jmock 传递请求参数,第二个问题是我使用 JNDI 在服务器启动时创建数据库连接,因此我的单元测试总是会失败DAO 调用已完成,因为单元测试在编译时执行。如何解决这两个问题并对该功能进行单元测试?

How can I unit test a MVC Model 2 application using junit and jmock?

I have a MVC Model 2 application fully functional but has zero unit tests. I am implementing unit tests around the application. I would like to unit test my controller servlet methods. The controller servlet calls the dao classes to peform CRUD operations. An example: User is presented with a login dialogbox and the user puts in userid/pwd and clicks "submit" button. The request is handled by the controller's processRequest() and validateLogin() methods which then queries the database through the DAO class and then finally the LoginBean is returned back with data if the login is successful.

My question is how do I unit test this kind of code?

Sample code provided below for better understanding of the problem.

---- ControllerServlet.java ----

public class ControllerServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

public void processRequest(HttpServletRequest request, HttpServletResponse response, String opcode) throws ServletException, IOException {
    String url = "index.jsp"; //default url
    HttpSession session = request.getSession();
    try {
        if (opcode.equalsIgnoreCase("authenticate")) {
            String firstName = GenericUtils.getParameter(request, "firstName");
            String lastName = GenericUtils.getParameter(request, "lastName");
            List userLst = validateLogin(firstName, lastName, request);
            boolean loginValid = CollectionUtils.isNotEmpty(userLst);
            request.setAttribute("loginValid", String.valueOf(loginValid)); //setting value in request attribute

            //if login is valid set the LoginBean in session
            if (loginValid) {
                LoginBean loginBean = (LoginBean) userLst.get(0);
                session.setAttribute("loginBean", loginBean);
                getAllProducts(request);
                url = "listProducts.jsp";
            } else {
                url = "login.jsp";
            }
        } 
}
catch.....
//some more code here
} 

public List validateLogin(String firstName, String lastName, HttpServletRequest request) throws ServletException, IOException {
    List userLst = new ArrayList();
    if (firstName.length() > 0 && lastName.length() > 0) {
        userLst = MasterDao.checkLoginValid(firstName, lastName);//DAO call goes here
    }
    return userLst;
}

}

How can I unit test this kind of stuff ? I tried to create a unit test using junit and jmock but I am not sure how to pass request parameters using jmock and the second problem is that I am using JNDI to create a db connection at server startup and hence my unit test will always fail where the DAO call is done because unit tests gets executed at compile time. How can I resolve these two issues and unit test this functionality?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜爱皱眉﹌ 2024-12-07 16:32:23

我会使用 Spring Web 模拟框架
http://static .springsource.org/spring/docs/current/javadoc-api/org/springframework/mock/web/package-summary.html

import org.agitar.mock.servlet.MockHttpServletRequest;
import org.agitar.mock.servlet.MockHttpServletResponse;
import org.junit.Before;
import org.springframework.mock.web.MockServletConfig;


public class ControllerServletTest {
    private ControllerServlet servlet;
    private MockServletConfig config;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @Before
    public void setUp()
            throws Exception {
        servlet = new ControllerServlet();
        config = new MockServletConfig();
        servlet.init(config);

        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void authenticate() throws Exception {
        request.putParameter("firstName", "Joe");
        request.putParameter("lastName", "Schmoe");

        // etc ...

        servlet.processRequest(request, response, "authenticate");

        // etc ...
    }

}

I'd use the Spring web mocking framework
http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/mock/web/package-summary.html

import org.agitar.mock.servlet.MockHttpServletRequest;
import org.agitar.mock.servlet.MockHttpServletResponse;
import org.junit.Before;
import org.springframework.mock.web.MockServletConfig;


public class ControllerServletTest {
    private ControllerServlet servlet;
    private MockServletConfig config;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @Before
    public void setUp()
            throws Exception {
        servlet = new ControllerServlet();
        config = new MockServletConfig();
        servlet.init(config);

        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void authenticate() throws Exception {
        request.putParameter("firstName", "Joe");
        request.putParameter("lastName", "Schmoe");

        // etc ...

        servlet.processRequest(request, response, "authenticate");

        // etc ...
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文