Example usage for org.springframework.mock.http.client MockClientHttpRequest getBodyAsString

List of usage examples for org.springframework.mock.http.client MockClientHttpRequest getBodyAsString

Introduction

In this page you can find the example usage for org.springframework.mock.http.client MockClientHttpRequest getBodyAsString.

Prototype

public String getBodyAsString() 

Source Link

Document

Return the body content interpreted as a UTF-8 string.

Usage

From source file:com.tyro.oss.pact.spring4.pact.consumer.ReturnExpect.java

private void createRequestExpectation(final ResponseEntity entity, final Type type) {
    for (int i = 1; i <= times; i++) {
        String bodyContent = extractBodyContent(entity, type);

        if (StringUtils.isNotBlank(schema)) {
            assertThat(bodyContent, matchesSchema(schema));
        }//from  www  .jav a 2  s .  co m

        mockRestServiceServer.expect(clientRequest -> {
            MockClientHttpRequest mockRequest = (MockClientHttpRequest) clientRequest;
            assertThat(mockRequest.getURI().toString(),
                    containsString(urlencode(restRequestDescriptor.getUrl())));
            assertThat(mockRequest.getMethod(), is(restRequestDescriptor.getMethod()));

            MediaType contentType1 = mockRequest.getHeaders().getContentType();
            String actualBody = mockRequest.getBodyAsString();
            String expectedBody = extractBodyContent(restRequestDescriptor.getRequest());
            if (contentType1 != null && "json".equalsIgnoreCase(contentType1.getSubtype())) {
                try {
                    JSONAssert.assertEquals(expectedBody, actualBody, false);
                } catch (JSONException e) {
                    try {
                        assertThat(actualBody, is(expectedBody));
                    } catch (AssertionError ex) {
                        throw new ComparisonFailure(e.getMessage(), expectedBody, actualBody);
                    }
                }
            } else {
                assertThat(actualBody, is(expectedBody));
            }

            assertRequestHeaders(mockRequest.getHeaders(), restRequestDescriptor.getRequest(),
                    additionalExpectedHeaders);
        }).andRespond(clientRequest -> {
            ClientHttpResponse response = MockRestResponseCreators.withStatus(entity.getStatusCode())
                    .headers(entity.getHeaders()).contentType(getContentType(entity)).body(bodyContent)
                    .createResponse(clientRequest);
            if (!withoutRecord) {
                try {
                    Pact pact = getPactFile();
                    getOrCreateWorkflowAndAddInteraction(pact, clientRequest, response);
                    Pact.writePact(pact, pactFile, objectConverter);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            return response;
        });
    }
}