servlet 的 JUnit 测试,当使用 HttpSession 时

JUnit test for servlet, when use HttpSession

我有这个 doPost 方法:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {

    response.setContentType("text/html");
    try {
        HttpSession session = request.getSession();
        synchronized (session) {
            Class.forName("org.postgresql.Driver");
            DataSource storage = DataSource.getInstance();
            if (session.getAttribute("role").toString().equals("admin")) {
                storage.update(request.getParameter("name"), request.getParameter("email"), request.getParameter("createDate"), request.getParameter("login"), request.getParameter("password"), request.getParameter("role"));
            } else if(session.getAttribute("role").toString().equals("user")) {
                storage.updateByUser(request.getParameter("name"), request.getParameter("email"), request.getParameter("createDate"), session.getAttribute("login").toString());
            }
            response.sendRedirect(String.format("%s/editUser", request.getContextPath()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我有这个测试:

@Test
public void editUser() throws SQLException {

    ServletEditUser servlet = new ServletEditUser();
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    DataSource.getInstance().add("test", "test", "test", "test", "test", "admin");

    when(request.getParameter("role")).thenReturn("admin");
    when(request.getParameter("login")).thenReturn("test");
    when(request.getParameter("name")).thenReturn("edit");
    when(request.getParameter("createDate")).thenReturn("edit");
    when(request.getParameter("password")).thenReturn("edit");

    servlet.doPost(request, response);
    List<User> users = DataSource.getInstance().getList();
    assertThat(DataSource.getInstance().getList().get(users.size() - 1).getName(), is("edit"));
}

我不明白,我应该如何测试我的 doPost 方法。我应该如何在 JUnit 测试中为会话设置属性?

答案:

在JUnit测试中,需要添加:

HttpSession session = mock(HttpSession.class);
when(request.getSession()).thenReturn(session);
when(request.getSession().getAttribute("role")).thenReturn("admin");

在JUnit测试中,需要添加:

HttpSession session = mock(HttpSession.class);
when(request.getSession()).thenReturn(session);
when(request.getSession().getAttribute("role")).thenReturn("admin");