LoginEndpoint { @Post public String login(HttpServletRequest request, HttpServletResponse response) { Optional<Session> session = authentication.auth(username, password, request.getRemoteAddr()); String continueUrl = request.getParameter("continue"); if (session.isPresent()) { Cookie sid = new Cookie("SID", session.get().value); sid.setPath("/"); response.addCookie(sid); return continueUrl; } else { try { return request.getRequestURI() + "?continue="+URLEncoder.encode(continueUrl,"UTF-8")+ "&errormessage="+URLEncoder.encode("Invalid username or password","UTF-8"); } catch (UnsupportedEncodingException e) { return request.getRequestURI() + "?continue="+URLEncoder.encode(continueUrl)+ "&errormessage="+URLEncoder.encode("Invalid username or password"); } } } @Inject  LoginEndpoint(ResourceOwnerAuthentication authentication); @Post String login(HttpServletRequest request, HttpServletResponse response); void setUsername(String username); void setPassword(String password); String getErrormessage(); void setErrormessage(String errormessage);  }
@Test public void happyPath() throws Exception { final Session session = new Session("session_value"); final Cookie cookie = new Cookie("SID", session.value); context.checking(new Expectations() {{ oneOf(request).getRemoteAddr(); will(Expectations.returnValue(remoteAddress)); oneOf(request).getParameter("continue"); will(returnValue("/movies")); oneOf(authentication).auth("FeNoMeNa", "parola", remoteAddress); will(Expectations.returnValue(Optional.of(session))); }}); pretendThatUserIsAuthorisedWith("FeNoMeNa", "parola"); String redirectPage = endpoint.login(request,response); response.assertContains(cookie); assertThat(redirectPage, is("/movies")); }
@Test public void wrongAuthentication() throws Exception { context.checking(new Expectations() {{ oneOf(request).getRemoteAddr(); will(Expectations.returnValue(remoteAddress)); oneOf(request).getParameter("continue"); will(returnValue("/xxx")); oneOf(request).getRequestURI(); oneOf(authentication).auth("Grigor", "dimitrov", remoteAddress); will(Expectations.returnValue(Optional.absent())); }}); pretendThatUserIsAuthorisedWith("Grigor", "dimitrov"); String redirectPage = endpoint.login(request, response); response.assertDoesNotExist("SID"); assertTrue(redirectPage.contains("?continue")); assertTrue(redirectPage.endsWith("&errormessage=Invalid+username+or+password")); }