Java: Tests custom JSON comparator

Task: Implement custom JSON comparator which will skip few fields

JSON (Example) - marked fields should be skipped in the test:

{
    “nextPage": false,
    "users": [
        {
            "id": "36797a00-852a-454e-a74d-14aca488aece",
            "username": "testUser_2”,
            … List of properties ...
            “profileKey”: null,
            “profileUrl": “null”,
            … List of properties ...
            "hasPassword": true
        },
        … List of users ...
    ]
}

Implementation:

Test:
    @Test
    @DatabaseSetup("/dataset/users/users.xml")
    public void testGetUsers() throws Exception {
        MvcResult mvcResult = mockMvc
                .perform(get(“http://localhost:8080/api/users"))
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn();

        String expected = FileUtil.loadFileToString("/json/users/users.json");
        JSONAssert.assertEquals(expected, mvcResult.getResponse().getContentAsString(), customArrayValueComparator);
        cleanAvatarFiles(mvcResult.getResponse().getContentAsString());
    }

Comparators:
    ArrayValueMatcher<Object> arrValMatch1 = new ArrayValueMatcher<>(new CustomComparator(
            JSONCompareMode.NON_EXTENSIBLE,
            new Customization(“*.profileUrl", (o1, o2) -> true), // Always correct value
            new Customization(“*.profileKey", (o1, o2) -> true)
    ));

    CustomComparator customArrayValueComparator = new CustomComparator(
            JSONCompareMode.STRICT,
            new Customization("users", arrValMatch1));

Done.

Leave a Reply

Your email address will not be published. Required fields are marked *




Enter Captcha Here :