问题
I want to test http request/response. So I use WireMock.
I want to stub response for specific request: Here code:
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));
}
Code is not compile because no object testClient. How I can get testClient object?
回答1:
testClient
is your client library for the API you are mocking.
Looks like you have copied directly from the examples which are indicative only.
Replace testClient
with the HTTP library of your choosing, for example 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);
}
来源:https://stackoverflow.com/questions/43639917/wiremock-stubbing-how-get-object-testclient