Example usage for org.springframework.mock.web MockHttpServletResponse getContentAsString

List of usage examples for org.springframework.mock.web MockHttpServletResponse getContentAsString

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletResponse getContentAsString.

Prototype

public String getContentAsString() throws UnsupportedEncodingException 

Source Link

Document

Get the content of the response body as a String , using the charset specified for the response by the application, either through HttpServletResponse methods or through a charset parameter on the Content-Type .

Usage

From source file:com.redblackit.web.server.EchoServletTest.java

/**
 * Do test//  w  w w . ja v a  2  s.  com
 *
 * @param method
 * @param hasBody if content should be expected
 */
private void doTest(String method, boolean hasBody) throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod(method);
    request.setRequestURI(this.requestURI);

    final String msg = "doTest:" + method + ":hasBody=" + hasBody;
    logger.debug(msg + ":this=" + this);

    for (String headerName : headersMap.keySet()) {
        List<String> values = headersMap.get(headerName);
        if (values.size() == 1) {
            request.addHeader(headerName, values.get(0));
        } else {
            request.addHeader(headerName, values);
        }
        Enumeration<String> headerValues = request.getHeaders(headerName);
        int hi = 0;
        while (headerValues.hasMoreElements()) {
            logger.debug(msg + "request:header[" + headerName + "," + hi + "]=" + headerValues.nextElement());
            ++hi;
        }

        Assert.assertTrue(msg + "TEST ERROR:request:header[" + headerName + "]=" + values
                + ":shouldn't be empty (" + values.getClass() + ")", hi > 0);

    }

    int expectedContentLength = 0;
    if (hasBody && body != null && body.length() > 0) {
        request.setContent(body.getBytes());
        expectedContentLength = request.getContentLength();
    }

    MockHttpServletResponse response = new MockHttpServletResponse();
    echoServlet.service(request, response);

    String responseBody = response.getContentAsString();

    Assert.assertEquals("response code:" + response, HttpServletResponse.SC_OK, response.getStatus());
    Assert.assertEquals("requestURI and Location", requestURI, response.getHeader("Location"));

    Map<String, List<String>> responseHeadersMap = new TreeMap<String, List<String>>();
    for (String headerName : response.getHeaderNames()) {
        List<String> values = response.getHeaders(headerName);
        int hi = 0;
        for (String value : values) {
            logger.debug(msg + ":response:header[" + headerName + "," + hi + "]=" + value);
            ++hi;
        }

        if (hi == 0) {
            logger.debug(msg + ":response:header[" + headerName + "]=" + values + ":is empty ("
                    + values.getClass() + ")");
            values = Arrays.asList(new String[] { "" });
        }

        if (!(headerName.equals("Location") || headerName.equals("Content-Length"))) {
            responseHeadersMap.put(headerName, values);
        }
    }

    Assert.assertEquals("headers (excluding Location and Content-Length)", headersMap, responseHeadersMap);
    if (hasBody) {
        Assert.assertEquals("body", (body == null ? "" : body), responseBody);
    } else {
        Assert.assertEquals("body", "", responseBody);
    }

    Assert.assertEquals("contentLength", expectedContentLength, response.getContentLength());

}

From source file:org.springsource.restbucks.payment.web.PaymentProcessIntegrationTest.java

/**
 * Triggers the payment of an {@link Order} by following the {@code payment} link and submitting a credit card number
 * to it. Verifies that we get a {@code 201 Created} and the response contains an {@code order} link. After the
 * payment has been triggered we fake a cancellation to make sure it is rejected with a {@code 404 Not found}.
 * //  w w w . ja  va 2  s  .c  o m
 * @param response
 * @return
 * @throws Exception
 */
private MockHttpServletResponse triggerPayment(MockHttpServletResponse response) throws Exception {

    String content = response.getContentAsString();
    LinkDiscoverer discoverer = getDiscovererFor(response);
    Link paymentLink = discoverer.findLinkWithRel(PAYMENT_REL, content);

    LOG.info(String.format("Discovered payment link pointing to %s", paymentLink));

    assertThat(paymentLink, not(nullValue()));

    LOG.info("Triggering payment");

    ResultActions action = mvc.perform(put(paymentLink.getHref()).//
            content("\"1234123412341234\"").//
            contentType(MediaType.APPLICATION_JSON).//
            accept(MediaTypes.HAL_JSON));

    MockHttpServletResponse result = action.andExpect(status().isCreated()). //
            andExpect(linkWithRelIsPresent(ORDER_REL)). //
            andReturn().getResponse();

    LOG.info("Payment triggered");

    // Make sure we cannot cheat and cancel the order after it has been payed
    LOG.info("Faking a cancel request to make sure it's forbidden");
    Link selfLink = discoverer.findLinkWithRel(Link.REL_SELF, content).expand();
    mvc.perform(delete(selfLink.getHref())).andExpect(status().isMethodNotAllowed());

    return result;
}

From source file:com.github.woonsan.katharsis.servlet.KatharsisFilterTest.java

@Test
public void testUnacceptableRequestContentType() throws Exception {
    MockFilterChain filterChain = new MockFilterChain();

    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath(null);/*from   w  ww.jav a 2  s. c  om*/
    request.setPathInfo(null);
    request.setRequestURI("/api/tasks/");
    request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
    request.addHeader("Accept", "application/xml");

    MockHttpServletResponse response = new MockHttpServletResponse();

    katharsisFilter.doFilter(request, response, filterChain);

    assertEquals(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, response.getStatus());
    String responseContent = response.getContentAsString();
    assertTrue(responseContent == null || "".equals(responseContent.trim()));
}

From source file:com.domingosuarez.boot.autoconfigure.jade4j.Jade4JAutoConfigurationTests.java

@Test
public void createLayoutFromConfigClass() throws Exception {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(Jade4JAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
    MockServletContext servletContext = new MockServletContext();
    context.setServletContext(servletContext);
    context.refresh();/*  w w w. j a  v a 2s .c  o  m*/

    JadeView view = (JadeView) context.getBean(JadeViewResolver.class).resolveViewName("demo", Locale.UK);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
    view.render(params(), request, response);
    String result = response.getContentAsString();
    assertTrue("Wrong result: " + result, result.contains("<title>Jade</title>"));
    assertTrue("Wrong result: " + result, result.contains("<h2>With user</h2>"));
    context.close();
}

From source file:newcontroller.handler.impl.DefaultResponseTest.java

@Test
public void testBodyJson() throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    Response res = new DefaultResponse(response,
            Arrays.asList(new StringHttpMessageConverter(), new GsonHttpMessageConverter()));
    HandlerBridge handlerBridge = res.body(Collections.singletonMap("name", "Joy"));
    handlerBridge.bridge(new DefaultRequest(new MockHttpServletRequest()), res);
    assertThat(response.getContentAsString(), is("{\"name\":\"Joy\"}"));
}

From source file:org.springsource.restbucks.training.payment.web.PaymentProcessIntegrationTest.java

/**
 * Follows the {@code order} link and asserts only the self link being present so that no further navigation is
 * possible anymore./*from ww w . j a v  a2s .  c o m*/
 * 
 * @param response
 * @throws Exception
 */
private void verifyOrderTaken(MockHttpServletResponse response) throws Exception {

    Link orderLink = getDiscovererFor(response).findLinkWithRel(ORDER_REL, response.getContentAsString());
    MockHttpServletResponse orderResponse = mvc.perform(get(orderLink.getHref())). //
            andExpect(status().isOk()). // //
            andExpect(linkWithRelIsPresent(Link.REL_SELF)). //
            andExpect(linkWithRelIsNotPresent(UPDATE_REL)). //
            andExpect(linkWithRelIsNotPresent(CANCEL_REL)). //
            andExpect(linkWithRelIsNotPresent(PAYMENT_REL)). //
            andExpect(jsonPath("$status", is("TAKEN"))). //
            andReturn().getResponse();

    log.info("Final order state: " + orderResponse.getContentAsString());
}

From source file:org.springsource.restbucks.training.payment.web.PaymentProcessIntegrationTest.java

/**
 * Concludes the {@link Order} by looking up the {@code receipt} link from the response and follows it. Triggers a
 * {@code DELETE} request susequently./*from ww  w . j  a v  a 2  s . c om*/
 * 
 * @param response
 * @return
 * @throws Exception
 */
private MockHttpServletResponse takeReceipt(MockHttpServletResponse response) throws Exception {

    Link receiptLink = getDiscovererFor(response).findLinkWithRel(RECEIPT_REL, response.getContentAsString());

    MockHttpServletResponse receiptResponse = mvc.perform(get(receiptLink.getHref())). //
            andExpect(status().isOk()). //
            andReturn().getResponse();

    log.info("Accessing receipt, got:" + receiptResponse.getContentAsString());
    log.info("Taking receipt");

    return mvc.perform(delete(receiptLink.getHref())). //
            andExpect(status().isOk()). //
            andReturn().getResponse();
}

From source file:org.springsource.restbucks.payment.web.PaymentProcessIntegrationTest.java

/**
 * Follows the {@code order} link and asserts only the self link being present so that no further navigation is
 * possible anymore./*w  w w.  j  a  v  a 2 s.  c om*/
 * 
 * @param response
 * @throws Exception
 */
private void verifyOrderTaken(MockHttpServletResponse response) throws Exception {

    Link orderLink = getDiscovererFor(response).findLinkWithRel(ORDER_REL, response.getContentAsString());
    MockHttpServletResponse orderResponse = mvc.perform(get(orderLink.expand().getHref())). //
            andExpect(status().isOk()). // //
            andExpect(linkWithRelIsPresent(Link.REL_SELF)). //
            andExpect(linkWithRelIsNotPresent(UPDATE_REL)). //
            andExpect(linkWithRelIsNotPresent(CANCEL_REL)). //
            andExpect(linkWithRelIsNotPresent(PAYMENT_REL)). //
            andExpect(jsonPath("$.status", is("Delivered"))). //
            andReturn().getResponse();

    LOG.info("Final order state: " + orderResponse.getContentAsString());
}

From source file:org.geogig.geoserver.rest.GeoGigWebAPIIntegrationTest.java

private MockHttpServletResponse assertResponse(String url, String expectedContent) throws Exception {

    MockHttpServletResponse sr = getAsServletResponse(url);
    assertEquals(sr.getContentAsString(), 200, sr.getStatus());

    String responseBody = sr.getContentAsString();

    assertNotNull(responseBody);/*w w w .  j  ava2  s  . c o m*/
    assertEquals(expectedContent, responseBody);
    return sr;
}

From source file:fr.paris.lutece.portal.web.upload.UploadServletTest.java

public void testDoPost_Files_NoHandler() throws Exception {
    MockHttpServletRequest request = getMultipartRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    MultipartHttpServletRequest multipartRequest = MultipartUtil.convert(10000, 10000, false, request);

    new UploadServlet().doPost(multipartRequest, response);

    String strResponseJson = response.getContentAsString();
    System.out.println(strResponseJson);

    String strRefJson = "{\"files\":[{\"fileName\":\"file1\",\"fileSize\":3}]}";
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode objectNodeRef = objectMapper.readTree(strRefJson);
    JsonNode objectNodeJson = objectMapper.readTree(strResponseJson);

    assertEquals(objectNodeRef, objectNodeJson);
}