假设应用程序依赖于位于外部服务器http://otherserver.com上的REST服务。为了进行测试,我想在JUnit环境中模拟外部rest调用(通过Wiremock)。启动单独的服务器需要时间且不容易。使用WiremockRule似乎是正确的方向。创建模拟控制器并不是一种优雅的方式,因为可以使用Wiremock。
例如:get("http://otherserver.com/service3/");
PS:当然,我知道可以通过Mockito模拟REST调用。
使用Wiremock模拟本地主机很容易。如何使用该代码模拟其他服务器和服务?我从流行的Baeldung示例中复制了部分内容。
例如:get("http://otherserver.com/service3/");
PS:当然,我知道可以通过Mockito模拟REST调用。
使用Wiremock模拟本地主机很容易。如何使用该代码模拟其他服务器和服务?我从流行的Baeldung示例中复制了部分内容。
public class WireMockDemo {
@Rule
public WireMockRule wireMockRule = new WireMockRule();
@Test
public void wireMockTestJunitOtherServer() {
try {
// **this does not work...**
configureFor("otherserver.com", 8080);
stubFor(get(urlPathMatching("/service2/.*"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("\"testing-library\": \"WireMock\"")));
// Test via simple client
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet("http://otherserver:8080/service2/test");
HttpResponse httpResponse = httpClient.execute(request);
String stringResponse = convertHttpResponseToString(httpResponse);
System.out.println( "Response = " + stringResponse);
// Test via JUnit
verify(getRequestedFor(urlEqualTo("/service2/wiremock")));
assertEquals(200, httpResponse.getStatusLine().getStatusCode());
assertEquals("application/json", httpResponse.getFirstHeader("Content-Type").getValue());
assertEquals("\"testing-library\": \"WireMock\"", stringResponse);
} catch( Exception e) {
e.printStackTrace();
}
}
// Support methods
private String convertHttpResponseToString(HttpResponse httpResponse) throws IOException {
InputStream inputStream = httpResponse.getEntity().getContent();
return convertInputStreamToString(inputStream);
}
private String convertInputStreamToString(InputStream inputStream) {
Scanner scanner = new Scanner(inputStream, "UTF-8");
String string = scanner.useDelimiter("\\Z").next();
scanner.close();
return string;
}
}