gpt4 book ai didi

Java Wiremock - 在测试期间模拟外部服务器

转载 作者:行者123 更新时间:2023-11-30 06:12:36 24 4
gpt4 key购买 nike

假设应用程序依赖于外部服务器上的 REST 服务,http://otherserver.com 。为了进行测试,我想在 JUnit 环境中模拟外部休息调用(通过 Wiremock)。启动单独的服务器既耗时又不容易。使用 WiremockRule 看起来是正确的方向。创建模拟 Controller 并不是一种优雅的方式,因为可以使用 Wiremock。

例如获取(“http://otherserver.com/service3/”);

PS:我当然知道我可以通过 Mockito 模拟 REST 调用。

使用 Wiremock 模拟 localhost 很容易。如何使用该代码来模拟其他服务器和服务?我从流行的 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;
}
}

最佳答案

您的应用程序代码不应包含 http://otherserver.com硬编码,它应该是可配置的。正常运行时它应该指向http://otherserver.com ,在测试模式下运行时应指向 http://localhost:<port>哪里<port>是您启动 Wiremock 服务器的位置(最好是动态的以避免端口冲突)

关于Java Wiremock - 在测试期间模拟外部服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49905750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com