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

tm1*_*701 6 java wiremock

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

例如 get(" 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Myk*_*rov 5

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