I often use WireMock when I want to perform a mocked test of the other party. Request matching can also be performed, which is very convenient.
stubFor(post(urlEqualTo("/mockurl"))
.withRequestBody(equalToJson(REQUEST_JSON_STRING))
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
.withBody(RESPONSE_JSON_STRING)));
If you write as above, RESPONSE_JSON_STRING
will be returned only when a JSON message that matches REQUEST_JSON_STRING
is accepted.
However,
--If the app issues a random string --If the app uses the current time
There are many items that are difficult to match.
{
"token": "uPx2bB9"
"accept_date": "2018-01-01T00:00:00.000Z",
}
Also, if you want to read REQUEST_JSON_STRING
from a file, you don't want to prepare as many files as there are variable items.
In such a case, add an argument to ʻequalToJson`.
StringValuePattern com.github.tomakehurst.wiremock.client.WireMock.equalToJson(String value, boolean ignoreArrayOrder, boolean ignoreExtraElements)
By setting ʻignoreExtraElements = true, elements that do not exist in
value` will be ignored.
stubFor(post(urlEqualTo("/mockurl"))
.withRequestBody(equalToJson(REQUEST_JSON_STRING, true, true))
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
.withBody(RESPONSE_JSON_STRING)));
If you set it as above,
REQUEST_JSON_STRING
:
{
"name": "hoge",
"data": {
"value": 1000
}
}
Actual request:
{
"name": "hoge",
"data": {
"token": "uPx2bB9",
"id": "abcde",
"value": 1000
}
}
But the matching is successful (the items token
and ʻidare ignored). You can also use
matchingJsonPath` to validate ignored items.
StringValuePattern com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath(String value)
If you want to verify that the element exists (When the current time or random character string is issued by the app and it is difficult to compare)
stubFor(post(urlEqualTo("/mockurl"))
.withRequestBody(equalToJson(REQUEST_JSON_STRING, true, true))
.withRequestBody(matchingJsonPath("$.data.token")) // "token"Verify that there is an item
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
.withBody(RESPONSE_JSON_STRING)));
If you also want to verify the value of an element (For example, when you want to verify variable elements according to test data)
stubFor(post(urlEqualTo("/mockurl"))
.withRequestBody(equalToJson(REQUEST_JSON_STRING, true, true))
.withRequestBody(matchingJsonPath("$.data[?(@.id == 'abcde')]")) // "id"Validate the value of
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
.withBody(RESPONSE_JSON_STRING)));
Recommended Posts