1

这是我模拟服务的实用程序类

public class MockService {


    public static void bootUpMockServices() throws IOException {

        String orderServiceSpecification = readFile("mappings/orderServicesSpecifications.json", Charset.defaultCharset());
        String singleOrder = readFile("mappings/singleOrder.json", Charset.defaultCharset());


        WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/orders"))
                .willReturn(WireMock.aResponse()
                        .withStatus(200)
                        .withBody(orderServiceSpecification)));

        WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/orders/1"))
                .willReturn(WireMock.aResponse()
                        .withStatus(200)
                        .withBody(singleOrder)));

    }

    public static String readFile(String path, Charset encoding) 
            throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }

}

正如您所看到的,我正在模拟一个 GET 调用/orders(包含所有订单)并使用正文响应并将所有订单保存在一个 json 文件中。

我还通过 GET 调用调用单个订单/orders/1。我正在使用文件中的 JSON 对象对其进行响应。但我希望它是动态的。就像当我点击它时一样orders/30,我应该动态地获取订单id=30并渲染它。

4

1 回答 1

1

目前,如果您想要您描述的那种动态行为,您需要编写一个 ResponseDefinitionTransformer 并将其注册到 WireMockServer 或 WireMockRule 在构造上。

这记录在这里:http ://wiremock.org/docs/extending-wiremock/#transforming-responses

此处的变压器实现示例: https ://github.com/tomakehurst/wiremock/blob/master/src/test/java/com/github/tomakehurst/wiremock/ResponseDefinitionTransformerAcceptanceTest.java#L208-L222

您尝试做的事情可以通过在 URL 正则表达式上匹配的存根映射以及/orders/(\d+)解析出数字部分然后修改bodyFileName.ResponseDefinition

于 2016-11-22T21:12:29.613 回答