Issue
I have this doPost method:
@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();
}
}
And i have this test:
@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"));
}
I'm don't understand, how I should test my doPost method. How I should setAttribute for session on JUnit test?
ANSWER:
In JUnit test, need to add:
HttpSession session = mock(HttpSession.class);
when(request.getSession()).thenReturn(session);
when(request.getSession().getAttribute("role")).thenReturn("admin");
Solution
In JUnit test, need to add:
HttpSession session = mock(HttpSession.class);
when(request.getSession()).thenReturn(session);
when(request.getSession().getAttribute("role")).thenReturn("admin");
Answered By - Anton Serdyuchenko