org.mockserver.model.HttpResponse.withBody()方法的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(14.7k)|赞(0)|评价(0)|浏览(79)

本文整理了Java中org.mockserver.model.HttpResponse.withBody()方法的一些代码示例,展示了HttpResponse.withBody()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpResponse.withBody()方法的具体详情如下:
包路径:org.mockserver.model.HttpResponse
类名称:HttpResponse
方法名:withBody

HttpResponse.withBody介绍

[英]Set response body to return as a string response body. The character set will be determined by the Content-Type header on the response. To force the character set, use #withBody(String,Charset).
[中]将响应主体设置为作为字符串响应主体返回。字符集将由响应上的内容类型标题确定。要强制使用字符集,请使用#withBody(字符串,字符集)。

代码示例

代码示例来源:origin: jamesdbloom/mockserver

private void setBody(HttpResponse httpResponse, FullHttpResponse fullHttpResponse) {
    if (fullHttpResponse.content().readableBytes() > 0) {
      byte[] bodyBytes = new byte[fullHttpResponse.content().readableBytes()];
      fullHttpResponse.content().readBytes(bodyBytes);
      if (bodyBytes.length > 0) {
        if (ContentTypeMapper.isBinary(fullHttpResponse.headers().get(CONTENT_TYPE))) {
          httpResponse.withBody(new BinaryBody(bodyBytes));
        } else {
          Charset requestCharset = ContentTypeMapper.getCharsetFromContentTypeHeader(fullHttpResponse.headers().get(CONTENT_TYPE));
          httpResponse.withBody(new String(bodyBytes, requestCharset));
        }
      }
    }
  }
}

代码示例来源:origin: jamesdbloom/mockserver

@Override
public void writeResponse(HttpRequest request, HttpResponseStatus responseStatus, String body, String contentType) {
  HttpResponse response = response()
    .withStatusCode(responseStatus.code())
    .withBody(body);
  if (body != null && !body.isEmpty()) {
    response.replaceHeader(header(CONTENT_TYPE.toString(), contentType + "; charset=utf-8"));
  }
  writeResponse(request, response, true);
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldReturnResponseByMatchingStringBody() throws IOException, URISyntaxException {
  // when
  getMockServerClient()
    .when(
      request()
        .withBody(
          exact("some_random_body")
        ),
      Times.exactly(2)
    )
    .respond(
      response()
        .withBody("some_string_body_response")
    );
  // then
  HttpClient httpClient = createHttpClient();
  HttpPost request = new HttpPost(
    new URIBuilder()
      .setScheme("http")
      .setHost("localhost")
      .setPort(getServerPort())
      .setPath(addContextToPath("some_path"))
      .build()
  );
  request.setEntity(new StringEntity("some_random_body"));
  HttpResponse response = httpClient.execute(request);
  assertThat(new String(EntityUtils.toByteArray(response.getEntity()), UTF_8), is("some_string_body_response"));
  assertThat(response.getStatusLine().getStatusCode(), is(OK_200.code()));
}

代码示例来源:origin: jamesdbloom/mockserver

@Override
public void writeResponse(HttpRequest request, HttpResponseStatus responseStatus, String body, String contentType) {
  HttpResponse response = response()
    .withStatusCode(responseStatus.code())
    .withReasonPhrase(responseStatus.reasonPhrase())
    .withBody(body);
  if (body != null && !body.isEmpty()) {
    response.replaceHeader(header(CONTENT_TYPE.toString(), contentType + "; charset=utf-8"));
  }
  writeResponse(request, response, true);
}

代码示例来源:origin: jamesdbloom/mockserver

/**
 * Static builder to create a response with a 200 status code and the string response body.
 *
 * @param body a string
 */
public static HttpResponse response(String body) {
  return new HttpResponse().withStatusCode(OK_200.code()).withReasonPhrase(OK_200.reasonPhrase()).withBody(body);
}

代码示例来源:origin: jamesdbloom/mockserver

public HttpResponse buildObject() {
  return new HttpResponse()
    .withStatusCode(statusCode)
    .withReasonPhrase(reasonPhrase)
    .withBody(body != null ? body.buildObject() : null)
    .withHeaders(headers)
    .withCookies(cookies)
    .withDelay((delay != null ? delay.buildObject() : null))
    .withConnectionOptions((connectionOptions != null ? connectionOptions.buildObject() : null));
}

代码示例来源:origin: jamesdbloom/mockserver

public HttpResponse clone() {
    return response()
      .withStatusCode(statusCode)
      .withReasonPhrase(reasonPhrase)
      .withBody(body)
      .withHeaders(headers.clone())
      .withCookies(cookies.clone())
      .withDelay(getDelay())
      .withConnectionOptions(connectionOptions);
  }
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldNotVerifyNoRequestsReceived() {
  // when
  mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body"));
  // then
  assertEquals(
    response()
      .withStatusCode(OK_200.code())
      .withReasonPhrase(OK_200.reasonPhrase())
      .withBody("some_body"),
    makeRequest(
      request()
        .withPath(calculatePath("some_path")),
      headersToIgnore)
  );
  try {
    mockServerClient.verifyZeroInteractions();
    fail();
  } catch (AssertionError ae) {
    assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE +
      "  \"method\" : \"GET\"," + NEW_LINE +
      "  \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE));
  }
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldReturnResponseWithOnlyBody() {
  // when
  mockServerClient.when(request()).respond(response().withBody("some_body"));
  // then
  // - in http
  assertEquals(
    response()
      .withStatusCode(OK_200.code())
      .withReasonPhrase(OK_200.reasonPhrase())
      .withBody("some_body"),
    makeRequest(
      request()
        .withPath(calculatePath("")),
      headersToIgnore)
  );
  // - in https
  assertEquals(
    response()
      .withStatusCode(OK_200.code())
      .withReasonPhrase(OK_200.reasonPhrase())
      .withBody("some_body"),
    makeRequest(
      request()
        .withSecure(true)
        .withPath(calculatePath("")),
      headersToIgnore)
  );
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldVerifyNotEnoughRequestsReceived() {
  // when
  mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body"));
  // then
  assertEquals(
    response()
      .withStatusCode(OK_200.code())
      .withReasonPhrase(OK_200.reasonPhrase())
      .withBody("some_body"),
    makeRequest(
      request()
        .withPath(calculatePath("some_path")),
      headersToIgnore)
  );
  try {
    mockServerClient.verify(request()
      .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2));
    fail();
  } catch (AssertionError ae) {
    assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + NEW_LINE +
      "  \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE +
      "}> but was:<{" + NEW_LINE +
      "  \"method\" : \"GET\"," + NEW_LINE +
      "  \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE));
  }
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldVerifyNoMatchingRequestsReceived() {
  // when
  mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body"));
  // then
  assertEquals(
    response()
      .withStatusCode(OK_200.code())
      .withReasonPhrase(OK_200.reasonPhrase())
      .withBody("some_body"),
    makeRequest(
      request()
        .withPath(calculatePath("some_path")),
      headersToIgnore)
  );
  try {
    mockServerClient.verify(request()
      .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2));
    fail();
  } catch (AssertionError ae) {
    assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE +
      "  \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE +
      "}> but was:<{" + NEW_LINE +
      "  \"method\" : \"GET\"," + NEW_LINE +
      "  \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE));
  }
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldVerifyTooManyRequestsReceived() {
  // when
  mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body"));
  // then
  assertEquals(
    response()
      .withStatusCode(OK_200.code())
      .withReasonPhrase(OK_200.reasonPhrase())
      .withBody("some_body"),
    makeRequest(
      request()
        .withPath(calculatePath("some_path")),
      headersToIgnore)
  );
  try {
    mockServerClient.verify(request()
      .withPath(calculatePath("some_path")), VerificationTimes.exactly(0));
    fail();
  } catch (AssertionError ae) {
    assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE +
      "  \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE +
      "}> but was:<{" + NEW_LINE +
      "  \"method\" : \"GET\"," + NEW_LINE +
      "  \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE));
  }
}

代码示例来源:origin: Netflix/eureka

@Test
public void testHeartbeatReplicationWithResponseBody() throws Exception {
  InstanceInfo remoteInfo = new InstanceInfo(this.instanceInfo);
  remoteInfo.setStatus(InstanceStatus.DOWN);
  byte[] responseBody = toGzippedJson(remoteInfo);
  serverMockClient.when(
      request()
          .withMethod("PUT")
          .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
          .withPath("/eureka/v2/apps/" + this.instanceInfo.getAppName() + '/' + this.instanceInfo.getId())
  ).respond(
      response()
          .withStatusCode(Status.CONFLICT.getStatusCode())
          .withHeader(header("Content-Type", MediaType.APPLICATION_JSON))
          .withHeader(header("Content-Encoding", "gzip"))
          .withBody(responseBody)
  );
  EurekaHttpResponse<InstanceInfo> response = replicationClient.sendHeartBeat(this.instanceInfo.getAppName(), this.instanceInfo.getId(), this.instanceInfo, null);
  assertThat(response.getStatusCode(), is(equalTo(Status.CONFLICT.getStatusCode())));
  assertThat(response.getEntity(), is(notNullValue()));
}

代码示例来源:origin: Netflix/eureka

@Test
public void testHeartbeatReplicationWithResponseBody() throws Exception {
  InstanceInfo remoteInfo = new InstanceInfo(this.instanceInfo);
  remoteInfo.setStatus(InstanceStatus.DOWN);
  byte[] responseBody = toGzippedJson(remoteInfo);
  serverMockClient.when(
      request()
          .withMethod("PUT")
          .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
          .withPath("/eureka/v2/apps/" + this.instanceInfo.getAppName() + '/' + this.instanceInfo.getId())
  ).respond(
      response()
          .withStatusCode(Status.CONFLICT.getStatusCode())
          .withHeader(header("Content-Type", MediaType.APPLICATION_JSON))
          .withHeader(header("Content-Encoding", "gzip"))
          .withBody(responseBody)
  );
  EurekaHttpResponse<InstanceInfo> response = replicationClient.sendHeartBeat(this.instanceInfo.getAppName(), this.instanceInfo.getId(), this.instanceInfo, null);
  assertThat(response.getStatusCode(), is(equalTo(Status.CONFLICT.getStatusCode())));
  assertThat(response.getEntity(), is(notNullValue()));
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldReturnResponseForRequestNotInSsl() {
  // when
  mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body"));
  // then
  // - in http
  assertEquals(
    response()
      .withStatusCode(OK_200.code())
      .withReasonPhrase(OK_200.reasonPhrase())
      .withBody("some_body"),
    makeRequest(
      request()
        .withPath(calculatePath("")),
      headersToIgnore)
  );
  // - in https
  assertEquals(
    response()
      .withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
      .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
    makeRequest(
      request()
        .withSecure(true)
        .withPath(calculatePath("")),
      headersToIgnore)
  );
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldReturnResponseForRequestInSsl() {
  // when
  mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body"));
  // then
  // - in http
  assertEquals(
    response()
      .withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
      .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
    makeRequest(
      request()
        .withPath(calculatePath("")),
      headersToIgnore)
  );
  // - in https
  assertEquals(
    response()
      .withStatusCode(OK_200.code())
      .withReasonPhrase(OK_200.reasonPhrase())
      .withBody("some_body"),
    makeRequest(
      request()
        .withSecure(true)
        .withPath(calculatePath("")),
      headersToIgnore)
  );
}

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldVerifySequenceOfRequestsReceived() {
  // when
  mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body"));
  // then
  assertEquals(
    response("some_body"),
    makeRequest(
      request().withPath(calculatePath("some_path_one")),
      headersToIgnore)
  );
  assertEquals(
    response("some_body"),
    makeRequest(
      request().withPath(calculatePath("some_path_two")),
      headersToIgnore)
  );
  assertEquals(
    response("some_body"),
    makeRequest(
      request().withPath(calculatePath("some_path_three")),
      headersToIgnore)
  );
  mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three")));
  mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")));
  mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three")));
}

代码示例来源:origin: Netflix/eureka

.withStatusCode(200)
        .withHeader(new Header("Content-Type", "application/json"))
        .withBody(fullFetchJson)
);
targetServerMockClient.client.when(
        .withStatusCode(200)
        .withHeader(new Header("Content-Type", "application/json"))
        .withBody(deltaFetchJson)
);

代码示例来源:origin: jamesdbloom/mockserver

@Test
public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() {
  // when
  mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body"));
  // then
  assertEquals(
    response("some_body"),
    makeRequest(
      request().withPath(calculatePath("some_path_one")),
      headersToIgnore)
  );
  assertEquals(
    notFoundResponse(),
    makeRequest(
      request().withPath(calculatePath("not_found")),
      headersToIgnore)
  );
  assertEquals(
    response("some_body"),
    makeRequest(
      request().withPath(calculatePath("some_path_three")),
      headersToIgnore)
  );
  mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three")));
  mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")));
  mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")));
  mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")));
}

代码示例来源:origin: Netflix/eureka

.withStatusCode(200)
        .withHeader(new Header("Content-Type", "application/json"))
        .withBody(fullFetchJson1)
);
targetServerMockClient.client.when(
        .withStatusCode(200)
        .withHeader(new Header("Content-Type", "application/json"))
        .withBody(fullFetchJson2)
);

相关文章