使用HttpSession时,对servlet进行JUnit测试

时间:2018-01-03 10:35:13

标签: java servlets junit mockito 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测试中为会话设置setAttribute?

1 个答案:

答案 0 :(得分:0)

在JUnit测试中,需要添加:

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