@Test public void testPutAndGet() throws ServletException, IOException { MovieServlet movieServlet = new MovieServlet(); movieServlet.init(); long movieId = testPut(movieServlet); testGet(movieServlet, movieId); }
@Test public void testGetWithNotExistingId() throws ServletException, IOException { MovieServlet movieServlet = new MovieServlet(); movieServlet.init(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getPathInfo()).thenReturn("/333"); movieServlet.doGet(request, response); verify(response, atLeastOnce()).setStatus(404); // not found }
@Test public void testGetWithBadId() throws ServletException, IOException { MovieServlet movieServlet = new MovieServlet(); movieServlet.init(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getPathInfo()).thenReturn("/some_string"); movieServlet.doGet(request, response); verify(response, atLeastOnce()).setStatus(400); // bad request }
private void testGet(MovieServlet movieServlet, long movieId) throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getPathInfo()).thenReturn("/" + movieId); StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); when(response.getWriter()).thenReturn(writer); movieServlet.doGet(request, response); String responseString = stringWriter.toString(); assertTrue(responseString.contains("\"id\":" + movieId + "," + TEST_MOVIE_JSON)); }
private long testPut(MovieServlet movieServlet) throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); BufferedReader reader = new BufferedReader(new StringReader("{" + TEST_MOVIE_JSON + "}")); when(request.getReader()).thenReturn(reader); StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); when(response.getWriter()).thenReturn(writer); movieServlet.doPut(request, response); String responseString = stringWriter.toString(); Pattern pattern = Pattern.compile("\\{\"id\":(\\d+)\\}"); Matcher matcher = pattern.matcher(responseString); assertTrue(matcher.matches()); return Long.parseLong(matcher.group(1)); }