'Asserting Rest Assured response with Json Unit

I'm currently using rest assured and Json-unit to assert a local json file against the requested rest assured response.

I currently have a before class method with my base uri.

I don't know how to make this assertion. I'm struggling with the json-unit documentation. Do I need to input a file first?

    @Test
    public void ApiaryTest1() throws Exception {

        when()

                .get("/test")
                .then()
                .statusCode(200);

        // compares two JSON documents
        assertJsonEquals("expected/test.json", "http://apiary/test");
        }


Solution 1:[1]

You need to:

  • Read in the resource with the JsonUnit API
  • Extract the response from rest assured to a variable
  • Assert you are already doing

Example:

Response response = when().get("<url>");
        response
                .then()
                .statusCode(200);

        // compares two JSON documents
        assertJsonEquals(resource("resource-inside-resources-folder.json"), response.asString());

Solution 2:[2]

For Restassured Kotlin DSL:

        When {
            get("http://nowjidev1vm01.ath.bskyb.com/calskyplussearch/health")
        } Then {
            statusCode(200)
        } Extract {
            assertJsonEquals(expectedBody, response().asString())
        }

Solution 3:[3]

It is easier than you think. Rest Assures is passing the entire body as string in case of a "body matcher" is specified. Therefore you can just use the jsonEquals matcher of json unit directly:

import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;

public class RestAssuredWithJsonUnit {

    @Test
    public void test() throws Exception {
        
        given().when().get("/api/service/v1").
                then().
                statusCode(200).
                body(jsonEquals(resource("resource-on-classpath.json")));

    }

    public static String resource(String resourceName) throws IOException {
        Objects.requireNonNull(resourceName, "'null' passed instead of resource name");
        return IOUtils.resourceToString(resourceName, UTF_8);
    }

Please note the implementation of the "resource" method. The one provided in ResourceUtils is using the system classloader, which did not found my resoulces unfortunately. IOUtils from commons-io does the job well!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 frevib
Solution 3 Tamas