0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WireMockでjsonをPOSTするリクエストとのマッピングルール

Posted at

wiremock-jre8-standalone-2.31.0.jar で確認。

POSTでリクエストボディがjsonとのマッピングルールの基本的な書き方。一通りの書き方のサンプルは公式ドキュメント https://wiremock.org/docs/request-matching/ にある。

equalToJsonにjsonをそのまま書く。

{
  "request": {
    "method": "POST",
    "url": "/post-sample",
    "bodyPatterns" : [ {
      "equalToJson" : {"first":"a", "second":"b", "list":[3,2,1]}
    } ]
  },
...

文字列リテラルとして指定も出来る。

...
    "bodyPatterns" : [ {
      "equalToJson" : "{\"first\" : \"a\",\"second\" : \"b\",\"list\" : [ 1, 2, 3 ]}",
...

デフォルトはstrictにマッチングするのでこれを弱めるオプションがある。

  • ignoreArrayOrder - 配列の順序が違っていてもマッチングする。
  • ignoreExtraElements - equalToJsonに無い要素が合ってもマッチングする。
...
    "bodyPatterns" : [ {
      "equalToJson" : "{\"first\" : \"a\",\"second\" : \"b\",\"list\" : [ 1, 2, 3 ]}",
      "ignoreArrayOrder" : true,
      "ignoreExtraElements" : true
    } ]
  },
...

プレースホルダーで任意の値でマッチングできる。以下の${json-unit.any-string}は任意の文字列にマッチングする。https://github.com/lukas-krecan/JsonUnit#typeplc にあるとおり、型ごとにいくつか用意されている。

...
    "bodyPatterns" : [ {
      "equalToJson" : {"first":"${json-unit.any-string}", "second":"b", "list":[3,2,1]},
...

なお、JSONのマッチングは https://github.com/lukas-krecan/JsonUnit を使ってる、と書いてあるので、もっと複雑な事をしたい場合はこっちのドキュメントとかソースコードとか見るのが良いと思う。

あと、ドキュメントにもある通りJSON Pathでのマッチングもできる。こちらも複雑なマッチングの式が書けるので、場合によって使い分けると思われる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?