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:org.auraframework.integration.test.http.resource.InlineJsTest.java

/**
 * Verify all content in script tag in aura:template is written into inlineJs.
 *
 * TODO: go over inline JS in aura:template and split the test into specific small cases.
 */// ww w.  ja  v a 2  s. c o  m
public void testInlineScriptInAuraTemplate() throws Exception {
    // Arrange
    if (contextService.isEstablished()) {
        contextService.endContext();
    }

    String appMarkup = String.format(baseApplicationTag, "template='aura:template'", "");
    DefDescriptor<ApplicationDef> appDesc = addSourceAutoCleanup(ApplicationDef.class, appMarkup);

    AuraContext context = contextService.startContext(AuraContext.Mode.DEV, AuraContext.Format.JS,
            AuraContext.Authentication.AUTHENTICATED, appDesc);

    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.addParameter("jwt", configAdapter.generateJwtToken());
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    InlineJs inlineJs = getInlineJs();

    // Act
    inlineJs.write(mockRequest, mockResponse, context);
    String content = mockResponse.getContentAsString();

    // Assert
    this.goldFileText(content);
}

From source file:org.springframework.data.rest.webmvc.cassandra.CassandraWebTests.java

/**
 * Verify that first creating (POST) and then replacing (PUT) a resource with a subset of fields only causes the
 * subset of fields to be changed inside Cassandra. NOTE: Cassandra doesn't handle nulls like traditional databases
 * and Spring Data Cassandra ignores {@literal null} fields.
 *
 * @throws Exception/*  w  ww .  ja  v  a2s .co m*/
 * @see DATAREST-414
 */
@Test
@Ignore
public void createThenPut() throws Exception {

    Employee employee = new Employee();
    employee.setId("123");
    employee.setFirstName("Frodo");
    employee.setLastName("Baggins");
    employee.setTitle("ring bearer");

    String employeeString = mapper.writeValueAsString(employee);

    Link employeeLink = client.discoverUnique("employees");

    MockHttpServletResponse response1 = postAndGet(employeeLink, employeeString, MediaType.APPLICATION_JSON);

    Link newlyMintedEmployeeLink = client.assertHasLinkWithRel("self", response1);
    Employee newlyMintedEmployee = mapper.readValue(response1.getContentAsString(), Employee.class);

    assertThat(newlyMintedEmployee.getFirstName(), equalTo(employee.getFirstName()));
    assertThat(newlyMintedEmployee.getLastName(), equalTo(employee.getLastName()));
    assertThat(newlyMintedEmployee.getTitle(), equalTo(employee.getTitle()));

    MockHttpServletResponse response2 = putAndGet(newlyMintedEmployeeLink, "{\"firstName\": \"Bilbo\"}",
            MediaType.APPLICATION_JSON);

    Employee refurbishedEmployee = mapper.readValue(response2.getContentAsString(), Employee.class);

    assertThat(refurbishedEmployee.getFirstName(), equalTo("Bilbo"));

    // Spring Data Cassandra doesn't apply null field values, hence these attributes won't change from
    // the original POST.
    assertThat(refurbishedEmployee.getLastName(), equalTo(employee.getLastName()));
    assertThat(refurbishedEmployee.getTitle(), equalTo(employee.getTitle()));
}

From source file:ch.rasc.extclassgenerator.ModelGeneratorBeanWithGenericValidationTest.java

@Test
public void testWriteModelHttpServletRequestHttpServletResponseClassOfQOutputFormatBoolean()
        throws IOException {
    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelGenerator.writeModel(new MockHttpServletRequest(), response, BeanWithGenericValidation.class,
            OutputFormat.EXTJS4, IncludeValidation.ALL, true);
    GeneratorTestUtil.compareExtJs4Code("BeanWithGenericValidation", response.getContentAsString(), true,
            false);/* w ww . j a v  a2  s  .  c o  m*/

    response = new MockHttpServletResponse();
    ModelGenerator.writeModel(new MockHttpServletRequest(), response, BeanWithGenericValidation.class,
            OutputFormat.TOUCH2, IncludeValidation.ALL, false);
    GeneratorTestUtil.compareTouch2Code("BeanWithGenericValidation", response.getContentAsString(), false,
            false);

    response = new MockHttpServletResponse();
    ModelGenerator.writeModel(new MockHttpServletRequest(), response, BeanWithGenericValidation.class,
            OutputFormat.EXTJS4, IncludeValidation.ALL, true);
    GeneratorTestUtil.compareExtJs4Code("BeanWithGenericValidation", response.getContentAsString(), true,
            false);

    response = new MockHttpServletResponse();
    ModelGenerator.writeModel(new MockHttpServletRequest(), response, BeanWithGenericValidation.class,
            OutputFormat.TOUCH2, IncludeValidation.ALL, true);
    GeneratorTestUtil.compareTouch2Code("BeanWithGenericValidation", response.getContentAsString(), true,
            false);
}

From source file:org.springframework.data.rest.webmvc.cassandra.CassandraWebTests.java

/**
 * Verify some basic creation (POST), updating (PATH) and replacing (PUT) functionality of Spring Data Cassandra
 * through Spring Data REST./*from  w ww .j av  a 2 s. co m*/
 *
 * @throws Exception
 * @see DATAREST-414
 */
@Test
@Ignore
public void createAnEmployee() throws Exception {

    Employee employee = new Employee();
    employee.setId("123");
    employee.setFirstName("Frodo");
    employee.setLastName("Baggins");
    employee.setTitle("ring bearer");

    String employeeString = mapper.writeValueAsString(employee);

    Link employeeLink = client.discoverUnique("employees");

    MockHttpServletResponse response = postAndGet(employeeLink, employeeString, MediaType.APPLICATION_JSON);

    Link newlyMintedEmployeeLink = client.assertHasLinkWithRel("self", response);
    Employee newlyMintedEmployee = mapper.readValue(response.getContentAsString(), Employee.class);

    assertThat(newlyMintedEmployee.getFirstName(), equalTo(employee.getFirstName()));
    assertThat(newlyMintedEmployee.getLastName(), equalTo(employee.getLastName()));
    assertThat(newlyMintedEmployee.getTitle(), equalTo(employee.getTitle()));

    MockHttpServletResponse response2 = patchAndGet(newlyMintedEmployeeLink, "{\"firstName\": \"Bilbo\"}",
            MediaType.APPLICATION_JSON);

    Link refurbishedEmployeeLink = client.assertHasLinkWithRel("self", response2);
    Employee refurbishedEmployee = mapper.readValue(response2.getContentAsString(), Employee.class);

    assertThat(refurbishedEmployee.getFirstName(), equalTo("Bilbo"));
    assertThat(refurbishedEmployee.getLastName(), equalTo(employee.getLastName()));
    assertThat(refurbishedEmployee.getTitle(), equalTo(employee.getTitle()));

    MockHttpServletResponse response3 = putAndGet(refurbishedEmployeeLink, "{\"lastName\": \"Jr.\"}",
            MediaType.APPLICATION_JSON);

    Employee lastEmployee = mapper.readValue(response3.getContentAsString(), Employee.class);

    assertThat(lastEmployee.getFirstName(), equalTo("Bilbo"));
    assertThat(lastEmployee.getLastName(), equalTo("Jr."));
    assertThat(lastEmployee.getTitle(), equalTo(employee.getTitle()));
}

From source file:net.ljcomputing.sr.controller.StatusReporterControllerTest.java

@Test
public void test014GetActivityByUuid() {
    try {// w  w w  .jav  a  2  s. c  om
        WorkBreakdownStructure persistedWbs = (WorkBreakdownStructure) expectedResults.getPostedRequestBody();
        Activity activity = persistedWbs.getActivities().get(0);
        String uuid = activity.getUuid();
        String url = "/sr/" + persistedWbs.getUuid() + "/activity/" + uuid;

        MockHttpServletRequestBuilder requestBuilder = get(url);
        requestBuilder.contentType(MediaType.APPLICATION_JSON);

        ResultActions result = mockMvc.perform(requestBuilder);
        MvcResult mvcResult = result.andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        assertTrue("failed to get activity by uuid",
                response.getStatus() >= 200 && response.getStatus() <= 299);

        logger.debug(response.getContentAsString());
    } catch (Exception e) {
        logger.error("test failed : ", e);
        fail(e.toString());
    }
}

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

/**
 * Test of doPost method, of class fr.paris.lutece.portal.web.upload.UploadServlet.
 */// w  ww  .  j  a v  a  2 s .com
public void testDoPost_NoFiles_NoHandler() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest(request, new HashMap(),
            new HashMap());

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

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

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

    assertEquals(objectNodeRef, objectNodeJson);
}

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

/**
 * Cancels the order by issuing a delete request. Verifies the resource being inavailable after that.
 * //from   www  .  ja v  a 2s  .com
 * @param response the response that retrieved an order resource
 * @throws Exception
 */
private void cancelOrder(MockHttpServletResponse response) throws Exception {

    String content = response.getContentAsString();

    Link selfLink = links.findLinkWithRel(Link.REL_SELF, content);
    Link cancellationLink = links.findLinkWithRel(CANCEL_REL, content);

    mvc.perform(delete(cancellationLink.getHref())).andExpect(status().isNoContent());
    mvc.perform(get(selfLink.getHref())).andExpect(status().isNotFound());
}

From source file:net.ljcomputing.sr.controller.StatusReporterControllerTest.java

@Test
public void test097DeleteActivity() {
    try {// w  w w.  java  2s.  c o m
        WorkBreakdownStructure persistedWbs = (WorkBreakdownStructure) expectedResults.getPostedRequestBody();
        Activity activity = persistedWbs.getActivities().get(0);
        String uuid = activity.getUuid();
        String url = "/sr/" + persistedWbs.getUuid() + "/activity/" + uuid;

        MockHttpServletRequestBuilder requestBuilder = delete(url);
        requestBuilder.contentType(MediaType.APPLICATION_JSON);

        ResultActions result = mockMvc.perform(requestBuilder);
        MvcResult mvcResult = result.andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        assertTrue("failed to delete activity by uuid",
                response.getStatus() >= 200 && response.getStatus() <= 299);

        logger.debug(response.getContentAsString());
    } catch (Exception e) {
        logger.error("test failed : ", e);
        fail(e.toString());
    }
}

From source file:ch.rasc.extclassgenerator.ModelGeneratorBeanWithValidationTest.java

@Test
public void testWriteModelHttpServletRequestHttpServletResponseClassOfQOutputFormatBoolean()
        throws IOException {
    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelGenerator.writeModel(new MockHttpServletRequest(), response, BeanWithValidation.class,
            OutputFormat.EXTJS4, IncludeValidation.ALL, true);
    GeneratorTestUtil.compareExtJs4Code("BeanWithValidation", response.getContentAsString(), true, false);

    response = new MockHttpServletResponse();
    ModelGenerator.writeModel(new MockHttpServletRequest(), response, BeanWithValidation.class,
            OutputFormat.TOUCH2, IncludeValidation.ALL, false);
    GeneratorTestUtil.compareTouch2Code("BeanWithValidation", response.getContentAsString(), false, false);

    response = new MockHttpServletResponse();
    ModelGenerator.writeModel(new MockHttpServletRequest(), response, BeanWithValidation.class,
            OutputFormat.EXTJS4, IncludeValidation.ALL, true);
    GeneratorTestUtil.compareExtJs4Code("BeanWithValidation", response.getContentAsString(), true, false);

    response = new MockHttpServletResponse();
    ModelGenerator.writeModel(new MockHttpServletRequest(), response, BeanWithValidation.class,
            OutputFormat.TOUCH2, IncludeValidation.ALL, true);
    GeneratorTestUtil.compareTouch2Code("BeanWithValidation", response.getContentAsString(), true, false);
}

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

/**
 * Follows the {@code orders} link returns the {@link Order}s found.
 * //from  w  ww  .j  a v  a2 s . co m
 * @param source
 * @return
 * @throws Exception
 */
private MockHttpServletResponse discoverOrdersResource(MockHttpServletResponse source) throws Exception {

    String content = source.getContentAsString();
    Link ordersLink = links.findLinkWithRel(ORDERS_REL, content);

    log.info("Root resource returned: " + content);
    log.info(String.format("Found orders link pointing to %s Following", ordersLink));

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

    log.info("Found orders: " + response.getContentAsString());
    return response;
}