com.github.tomakehurst.wiremock.client.WireMock类的使用及代码示例

x33g5p2x  于2022-02-03 转载在 其他  
字(11.9k)|赞(0)|评价(0)|浏览(128)

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

WireMock介绍

暂无

代码示例

代码示例来源:origin: resilience4j/resilience4j

private void setupStub(int responseCode) {
    stubFor(get(urlPathEqualTo("/greeting"))
        .willReturn(aResponse()
            .withStatus(responseCode)
            .withHeader("Content-Type", "text/plain")
            .withBody("hello world")));
  }
}

代码示例来源:origin: apache/drill

private void setupGetStubs() {
 wireMockRule.stubFor(get(urlEqualTo("/api/suggest?type=metrics&max=" + Integer.MAX_VALUE))
   .willReturn(aResponse()
     .withStatus(200)
     .withHeader("Content-Type", "application/json")
     .withBody(SAMPLE_DATA_FOR_GET_TABLE_NAME_REQUEST)));
 wireMockRule.stubFor(get(urlEqualTo("/api/query?start=47y-ago&m=sum:warp.speed.test"))
   .willReturn(aResponse()
     .withStatus(200)
     .withBody(SAMPLE_DATA_FOR_GET_TABLE_REQUEST)
   ));
}

代码示例来源:origin: apache/drill

private void setupPostStubs() {
 wireMockRule.stubFor(post(urlEqualTo("/api/query"))
   .withRequestBody(equalToJson(POST_REQUEST_WITHOUT_TAGS))
   .willReturn(aResponse()
     .withStatus(200)
     .withHeader("Content-Type", "application/json")
     .withBody(SAMPLE_DATA_FOR_GET_TABLE_REQUEST)));
 wireMockRule.stubFor(post(urlEqualTo("/api/query"))
   .withRequestBody(equalToJson(POST_REQUEST_WITH_TAGS))
   .willReturn(aResponse()
 wireMockRule.stubFor(post(urlEqualTo("/api/query"))
   .withRequestBody(equalToJson(DOWNSAMPLE_REQUEST_WTIHOUT_TAGS))
   .willReturn(aResponse()
 wireMockRule.stubFor(post(urlEqualTo("/api/query"))
     .withRequestBody(equalToJson(END_PARAM_REQUEST_WTIHOUT_TAGS))
     .willReturn(aResponse()
 wireMockRule.stubFor(post(urlEqualTo("/api/query"))
   .withRequestBody(equalToJson(DOWNSAMPLE_REQUEST_WITH_TAGS))
   .willReturn(aResponse()
 wireMockRule.stubFor(post(urlEqualTo("/api/query"))
     .withRequestBody(equalToJson(END_PARAM_REQUEST_WITH_TAGS))
     .willReturn(aResponse()
 wireMockRule.stubFor(post(urlEqualTo("/api/query"))
   .withRequestBody(equalToJson(REQUEST_TO_NONEXISTENT_METRIC))

代码示例来源:origin: resilience4j/resilience4j

@Test(expected = IOException.class)
public void shouldNotCatchEnqueuedCallExceptionsInRateLimiter() throws Throwable {
  stubFor(get(urlPathEqualTo("/greeting"))
          .willReturn(aResponse()
                    .withStatus(200)
                    .withFixedDelay(400)));
  EnqueueDecorator.enqueue(service.greeting());
}

代码示例来源:origin: alfa-laboratory/akita

@Test
void sendHttpRequestPost() throws Exception {
  stubFor(post(urlEqualTo("/post/resource"))
    .willReturn(aResponse()
      .withStatus(200)
      .withHeader("Content-Type", "text/xml")
      .withBody("TEST_BODY")));
  api.sendHttpRequestWithoutParams("POST", "/post/resource", "RESPONSE_POST_BODY");
  assertThat(akitaScenario.getVar("RESPONSE_POST_BODY"), equalTo("TEST_BODY"));
}

代码示例来源:origin: palantir/atlasdb

@Before
public void setup() {
  String testNumberAsString = Integer.toString(TEST_NUMBER);
  availableServer.stubFor(ENDPOINT_MAPPING.willReturn(aResponse().withStatus(200).withBody(testNumberAsString)));
  proxyServer.stubFor(ENDPOINT_MAPPING.willReturn(aResponse().withStatus(200).withBody(testNumberAsString)));
  availablePort = availableServer.port();
  unavailablePort = unavailableServer.port();
  proxyPort = proxyServer.port();
  bothUris = ImmutableSet.of(
      getUriForPort(unavailablePort),
      getUriForPort(availablePort));
}

代码示例来源:origin: kamax-matrix/mxisd

@Test
public void forNameNotFound() {
  stubFor(post(urlEqualTo(displayNameEndpoint))
      .willReturn(aResponse()
          .withStatus(404)
      )
  );
  Optional<String> v = p.getDisplayName(userId);
  verify(postRequestedFor(urlMatching(displayNameEndpoint))
      .withHeader("Content-Type", containing(ContentType.APPLICATION_JSON.getMimeType()))
      .withRequestBody(equalTo(GsonUtil.get().toJson(new JsonProfileRequest(userId))))
  );
  assertFalse(v.isPresent());
}

代码示例来源:origin: geotools/geotools

@Test
  public void testBasicHeader() throws IOException {
    stubFor(
        get(urlEqualTo("/test"))
            .willReturn(
                aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "text/xml")
                    .withBody("<response>Some content</response>")));

    String longPassword = String.join("", Collections.nCopies(10, "0123456789"));
    String userName = "user";
    SimpleHttpClient client = new SimpleHttpClient();
    client.setUser(userName);
    client.setPassword(longPassword);
    client.get(new URL("http://localhost:" + wireMockRule.port() + "/test"));

    String encodedCredentials =
        "dXNlcjowMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5";
    verify(
        getRequestedFor(urlEqualTo("/test"))
            .withHeader("Authorization", equalTo("Basic " + encodedCredentials)));
  }
}

代码示例来源:origin: org.apache.logging.log4j/log4j-core

@Test
public void testAppend() throws Exception {
  wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
    .willReturn(SUCCESS_RESPONSE));
  final Appender appender = HttpAppender.newBuilder()
    .withName("Http")
    .withLayout(JsonLayout.createDefaultLayout())
    .setConfiguration(ctx.getConfiguration())
    .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
    .build();
  appender.append(createLogEvent());
  wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
    .withHeader("Host", containing("localhost"))
    .withHeader("Content-Type", containing("application/json"))
    .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}

代码示例来源:origin: palantir/atlasdb

@Test
public void propagatesBackupTimestampToFastForwardOnRemoteService() {
  wireMockRule.stubFor(TEST_MAPPING.willReturn(aResponse().withStatus(204)));
  TimeLockMigrator migrator =
      TimeLockMigrator.create(
          MetricsManagers.createForTests(),
          timelockConfig.toNamespacedServerList(), invalidator, USER_AGENT);
  migrator.migrate();
  wireMockRule.verify(getRequestedFor(urlEqualTo(PING_ENDPOINT)));
  verify(invalidator, times(1)).backupAndInvalidate();
  wireMockRule.verify(postRequestedFor(urlEqualTo(TEST_ENDPOINT)));
}

代码示例来源:origin: allegro/hermes

public void expectMessages(List<String> messages) {
  receivedRequests.clear();
  expectedMessages = messages;
  messages.forEach(m -> listener
    .register(
      post(urlEqualTo(path))
      .willReturn(aResponse().withStatus(returnedStatusCode).withFixedDelay(delay))));
}

代码示例来源:origin: ocadotechnology/newrelic-alerts-configurator

private void newRelicReturnsApplications() throws UnsupportedEncodingException {
  String queryParam = URLEncoder.encode("filter[name]", UTF_8.name());
  WIRE_MOCK.addStubMapping(
      get(urlPathEqualTo("/v2/applications.json"))
          .withQueryParam(queryParam, equalTo("application_name"))
          .withHeader("X-Api-Key", equalTo("secret"))
          .willReturn(aResponse()
              .withStatus(SC_OK)
              .withHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON)
              .withBody(applications)
          ).build());
}

代码示例来源:origin: kptfh/feign-reactive

@Test
 public void testPayBill_success() throws JsonProcessingException {

  Bill bill = Bill.makeBill(new OrderGenerator().generate(30));

  wireMockRule.stubFor(post(urlEqualTo("/icecream/bills/pay"))
      .withRequestBody(equalTo(TestUtils.MAPPER.writeValueAsString(bill)))
      .willReturn(aResponse().withStatus(200)
          .withHeader("Content-Type", "application/json")));

  Mono<Void> result = client.payBill(bill);
  StepVerifier.create(result)
    .expectNextCount(0)
    .verifyComplete();
 }
}

代码示例来源:origin: palantir/atlasdb

@Test
public void ifOneServerResponds503WithNoRetryHeaderTheRequestIsRerouted() {
  unavailableServer.stubFor(ENDPOINT_MAPPING.willReturn(aResponse().withStatus(503)));
  TestResource client = AtlasDbHttpClients.createProxyWithFailover(new MetricRegistry(),
      NO_SSL,
      Optional.empty(), bothUris, TestResource.class);
  int response = client.getTestNumber();
  assertThat(response, equalTo(TEST_NUMBER));
  unavailableServer.verify(getRequestedFor(urlMatching(TEST_ENDPOINT)));
}

代码示例来源:origin: aws/aws-sdk-java-v2

private void stubForMockRequest(int returnCode) {
  ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(returnCode)
                              .withHeader("Some-Header", "With Value")
                              .withBody("hello");
  if (returnCode >= 300 && returnCode <= 399) {
    responseBuilder.withHeader("Location", "Some New Location");
  }
  stubFor(any(urlPathEqualTo("/")).willReturn(responseBuilder));
}

代码示例来源:origin: hibernate/hibernate-search

@Test
public void tinyPayload() throws Exception {
  SearchConfigurationForTest configuration = createConfiguration();
  wireMockRule.stubFor( post( urlPathLike( "/myIndex/myType" ) )
      .willReturn( elasticsearchResponse().withStatus( 200 ) ) );
  try ( ElasticsearchClient client = createClient( configuration ) ) {
    doPost( client, "/myIndex/myType", produceBody( 1 ) );
    wireMockRule.verify(
        postRequestedFor( urlPathLike( "/myIndex/myType" ) )
            .withoutHeader( "Transfer-Encoding" )
            .withHeader( "Content-length", equalTo( String.valueOf( BODY_PART_BYTE_SIZE ) ) )
        );
  }
}

代码示例来源:origin: palantir/atlasdb

@Before
public void setUp() {
  when(invalidator.backupAndInvalidate()).thenReturn(BACKUP_TIMESTAMP);
  wireMockRule.stubFor(PING_MAPPING.willReturn(aResponse()
      .withStatus(200)
      .withBody(TimestampManagementService.PING_RESPONSE)
      .withHeader("Content-Type", "text/plain"))
      .inScenario(SCENARIO)
      .whenScenarioStateIs(Scenario.STARTED)
      .willSetStateTo(Scenario.STARTED));
  String serverUri = String.format("http://%s:%s",
      WireMockConfiguration.DEFAULT_BIND_ADDRESS,
      wireMockRule.port());
  ServerListConfig defaultServerListConfig = ImmutableServerListConfig.builder().addServers(serverUri).build();
  timelockConfig = ImmutableTimeLockClientConfig.builder()
      .client("testClient")
      .serversList(defaultServerListConfig)
      .build();
}

代码示例来源:origin: kptfh/feign-reactive

@Test
public void shouldThrowRetryException() {
 wireMockRule.stubFor(get(urlEqualTo("/icecream/orders/1"))
   .withHeader("Accept", equalTo("application/json"))
   .willReturn(aResponse().withStatus(HttpStatus.SC_SERVICE_UNAVAILABLE)));
 IcecreamServiceApi client = builder()
   .statusHandler(throwOnStatus(
     status -> status == HttpStatus.SC_SERVICE_UNAVAILABLE,
     (methodTag, response) -> new RetryableException("Should retry on next node", null)))
   .target(IcecreamServiceApi.class, "http://localhost:" + wireMockRule.port());
 StepVerifier.create(client.findFirstOrder())
   .expectError(RetryableException.class);
}

代码示例来源:origin: palantir/atlasdb

@Test
public void userAgentsPresentOnRequestsToTimelockServer() {
  setUpTimeLockBlockInInstallConfig();
  availableServer.stubFor(post(urlMatching("/")).willReturn(aResponse().withStatus(200).withBody("3")));
  availableServer.stubFor(TIMELOCK_LOCK_MAPPING.willReturn(aResponse().withStatus(200).withBody("4")));
  verifyUserAgentOnTimelockTimestampAndLockRequests();
}

代码示例来源:origin: palantir/atlasdb

@Test
public void asyncMigrationProceedsIfTimeLockInitiallyUnavailable() throws InterruptedException {
  String nowSucceeding = "nowSucceeding";
  wireMockRule.stubFor(PING_MAPPING.inScenario(SCENARIO)
      .whenScenarioStateIs(Scenario.STARTED)
      .willReturn(aResponse().withStatus(500))
      .willSetStateTo(nowSucceeding));
  wireMockRule.stubFor(PING_MAPPING.inScenario(SCENARIO)
      .whenScenarioStateIs(nowSucceeding)
      .willReturn(aResponse().withStatus(204)));
  wireMockRule.stubFor(TEST_MAPPING.willReturn(aResponse().withStatus(204)));
  TimeLockMigrator migrator =
      TimeLockMigrator.create(
          MetricsManagers.createForTests(),
          () -> timelockConfig.toNamespacedServerList(), invalidator, USER_AGENT, true);
  migrator.migrate();
  Awaitility.await()
      .atMost(30, TimeUnit.SECONDS)
      .pollInterval(1, TimeUnit.SECONDS)
      .until(migrator::isInitialized);
  wireMockRule.verify(getRequestedFor(urlEqualTo(PING_ENDPOINT)));
  verify(invalidator, times(1)).backupAndInvalidate();
  wireMockRule.verify(postRequestedFor(urlEqualTo(TEST_ENDPOINT)));
}

相关文章