### Question:
AuthServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { String action = req.getParameter("action"); try { if (action.equals("signin")) { String login = req.getParameter("login"); String password = req.getParameter("password"); User foundUser = this.validator.findByLogin(login); if (foundUser != null && foundUser.getPassword().equals(password)) { req.getSession().setAttribute("loginRole", new LoginRole(foundUser)); resp.sendRedirect(String.format("%s/list", req.getContextPath())); } else { req.setAttribute("error", "Invalid login or password"); req.getRequestDispatcher("/WEB-INF/views/auth.jsp").forward(req, resp); } } else if (req.getParameter("action").equals("signout")) { req.getSession().invalidate(); resp.sendRedirect(String.format("%s/signin", req.getContextPath())); } } catch (ServletException | IOException e) { LOG.error(e.getMessage(), e); } }    }### Answer:
@Test public void ifLoginRootThenSessionShouldBeSetAttributeLoginRole() throws IOException { HttpSession session = mock(HttpSession.class); when(this.request.getSession()).thenReturn(session); when(this.request.getParameter("action")).thenReturn("signin"); when(this.request.getParameter("login")).thenReturn("root"); when(this.request.getParameter("password")).thenReturn("root"); when(this.request.getRequestDispatcher("/WEB-INF/views/auth.jsp")).thenReturn(this.dispatcher); User forMock = new User(); forMock.setLogin("root"); forMock.setRole("ADMINISTRATOR"); testServlet.doPost(this.request, this.response); verify(session).setAttribute("loginRole", testServlet.new LoginRole(forMock)); verify(this.response).sendRedirect(this.request.getContextPath() + "/list"); }
@Test public void ifSignInByNonExistentUserThenServletForwardRequest() throws ServletException, IOException { when(this.request.getParameter("action")).thenReturn("signin"); when(this.request.getParameter("login")).thenReturn("nonExistentUsr"); when(this.request.getParameter("password")).thenReturn("invalidPassword"); when(this.request.getRequestDispatcher("/WEB-INF/views/auth.jsp")).thenReturn(this.dispatcher); testServlet.doPost(this.request, this.response); verify(this.request).setAttribute("error", "Invalid login or password"); verify(this.dispatcher).forward(this.request, this.response); }
@Test public void ifSiguOutThenServletSendRedirectAndInvalidateSession() throws IOException { HttpSession session = mock(HttpSession.class); when(this.request.getParameter("action")).thenReturn("signout"); when(this.request.getSession()).thenReturn(session); testServlet.doPost(this.request, this.response); verify(this.response).sendRedirect(this.request.getContextPath() + "/signin"); verify(session).invalidate(); }