简体   繁体   English

WireMock - 包含 JSON 属性的请求的存根

[英]WireMock - Stub for Request Containing JSON Attribute

I'm trying to mock for the same request URL (multiple times), with different responses according to the JSON Body content.我试图模拟相同的请求 URL(多次),根据 JSON Body 内容有不同的响应。

My Request JSON is build dynamically so I can't statically use the equalToJson function on the Mock.我的请求 JSON 是动态构建的,所以我不能在 Mock 上静态使用equalToJson函数。

I have the same JSON like this:我有这样的 JSON:

{
    // Changes according to the request
    "task": "TEXT_ENTITY_RECOGNITION",
    "category": "TEXT",
    "data": content
}

What's the best approach for the wireMockServer stubs? wireMockServer存根的最佳方法是什么?

I'm trying something like this我正在尝试这样的事情

wireMockServer.stubFor(post(urlEqualTo("/request"))
                        .withRequestBody(containing("TEXT_ENTITY_RECOGNITION"))
                        .withHeader("Content-Type", equalTo("application/json"))
                        .willReturn(aResponse()
                                .withStatus(201)
                                .withHeader("Content-Type", "application/json")
.withBody(mockedJson)));

I have not found any sample of anything like this on the documentation.我没有在文档中找到任何类似的样本。 Thanks!谢谢!

WireMock provides Several Content Pattern EqualToPattern and ContainsPattern are few of them. WireMock 提供了几种内容模式 EqualToPattern 和 ContainsPattern 是其中的几个。 Try Something like :尝试类似的东西:

StringValuePattern urlPattern = new EqualToJsonPattern("/request", true, true);
        MappingBuilder mappingBuilder = WireMock.post(new UrlPattern(urlPattern, false));
        StringValuePattern requestBodyPattern = new ContainsPattern("TEXT_ENTITY_RECOGNITION");
        mappingBuilder.withRequestBody(requestBodyPattern).withHeader("Content-Type", new EqualToJsonPattern("application/json", true, true));
        ResponseDefinitionBuilder response = WireMock.aResponse().withBody("Successful Custom Body Response").withStatus(201).withHeader("Content-Type", "application/json");
        mappingBuilder.willReturn(response);
        wireMockServer.stubFor(mappingBuilder);

This works well for me.这对我很有效。

Wiremock has the containing function, the way for calling is WireMock.containing Wiremock 有包含函数,调用方式为 WireMock. contains

wireMockServer.stubFor(post(urlEqualTo("/request"))
                    .withRequestBody(WireMock.containing("TEXT_ENTITY_RECOGNITION"))
                    .withHeader("Content-Type", equalTo("application/json"))
                    .willReturn(aResponse()
                            .withStatus(201)
                            .withHeader("Content-Type", "application/json")
                            .withBody(mockedJson)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM