WireMock:存根 - 如何获取对象 "testClient"?
WireMock: Stubbing - How get object "testClient"?
我想测试 http request/response。所以我使用 WireMock。
我想存根特定请求的响应:
此处代码:
public class WireMockPersons {
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);
@Test
public void exactUrlOnly() {
stubFor(get(urlEqualTo("/some/thing"))
.willReturn(aResponse()
.withHeader("Content-Type", "text/plain")
.withBody("Hello world!")));
assertThat(testClient.get("/some/thing").statusCode(), is(200));
assertThat(testClient.get("/some/thing/else").statusCode(), is(404));
}
代码未编译,因为没有对象 testClient。如何获得 testClient 对象?
testClient
是您正在模拟的 API 的客户端库。
看起来您是直接从示例中复制的,这些示例仅供参考。
将 testClient
替换为您选择的 HTTP 库,例如 HttpClient
。
String url = "http://localhost:8089/some/thing";
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpGet get = new HttpGet(url);
HttpEntity entity = client.execute(get).getEntity();
return EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
throw new RuntimeException("Unable to call " + url, e);
}
我想测试 http request/response。所以我使用 WireMock。
我想存根特定请求的响应: 此处代码:
public class WireMockPersons {
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);
@Test
public void exactUrlOnly() {
stubFor(get(urlEqualTo("/some/thing"))
.willReturn(aResponse()
.withHeader("Content-Type", "text/plain")
.withBody("Hello world!")));
assertThat(testClient.get("/some/thing").statusCode(), is(200));
assertThat(testClient.get("/some/thing/else").statusCode(), is(404));
}
代码未编译,因为没有对象 testClient。如何获得 testClient 对象?
testClient
是您正在模拟的 API 的客户端库。
看起来您是直接从示例中复制的,这些示例仅供参考。
将 testClient
替换为您选择的 HTTP 库,例如 HttpClient
。
String url = "http://localhost:8089/some/thing";
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpGet get = new HttpGet(url);
HttpEntity entity = client.execute(get).getEntity();
return EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
throw new RuntimeException("Unable to call " + url, e);
}