alexcuesta

My tech blog

Wiremock.equalToJson

leave a comment »

Are you wondering how to match a specific element in your body request with Wiremock?

I was. I always struggled to find proper documentation about how to use this matcher. I am going to tell you how.

Given the following json request:

{ 
    "searchContext": {
        "currency": "USD"
        "config": {
            "price": {
                "parts": [
                    "BASE",
                    "DISPLAY_TAX"
                ]
            }
        }
    },
    "searchCriteria": {
        "city": "London",
        "checkin": "13/03/2016",
        "checkout": "13/03/2016"
    }
}

Let’s say I want to match “parts has BASE and DISPLAY_TAX”. The way to do it is by removing all the sibling elements you are not interested in and set the right JSONCompareMode.

{ 
    "searchContext": {
        "config": {
            "price": {
                "parts": [
                    "BASE",
                    "DISPLAY_TAX"
                ]
            }
        }
    }
}

So the actual code to match this with Wiremock is:

mappingBuilder.withRequestBody(equalToJson("{ \n" +
                "    \"searchContext\": {\n" +
                "        \"config\": {\n" +
                "            \"price\": {\n" +
                "                \"parts\": [\n" +
                "                    \"BASE\",\n" +
                "                    \"DISPLAY_TAX\"\n" +
                "                ]\n" +
                "            }\n" +
                "        }\n" +
                "    }\n" +
                "}", JSONCompareMode.LENIENT));

LENIENT means Extensible (we can have more elements around ours) and no Strict Order on lists. If you swap the order of the elements on the list “parts” this will work.

Written by alexcuesta

March 15, 2016 at 3:23 pm

Posted in Java, Testing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: