Ejemplo n.º 1
0
  @Test
  public void testPutAndGet() throws ServletException, IOException {
    MovieServlet movieServlet = new MovieServlet();
    movieServlet.init();

    long movieId = testPut(movieServlet);
    testGet(movieServlet, movieId);
  }
Ejemplo n.º 2
0
  @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
  }
Ejemplo n.º 3
0
  @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
  }
Ejemplo n.º 4
0
  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));
  }
Ejemplo n.º 5
0
  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));
  }