Search code examples
javajsonjunit-jupiterspring-webtestclient

WebTestClient assertThat json has only specific keys


I'm testing my endpoints like so:

        webTestClient.get().uri(BASE_URL).
            .exchange().expectStatus().isOk().expectBody()
            .jsonPath("$.name").isEqualTo("test1")
            .jsonPath("$.street").isEqualTo("test1")
            .jsonPath("$.id").isEqualTo(1);

Is there any way I can make sure that the json has only those 3 fields and not more?


Solution

  • Solved it by checking the size of the json properties. Not exactly what I wanted (because now I have to change 2 values of something changes), but it's still a viable solution:

    .jsonPath("$.length()").isEqualTo(4);
    

    Hamcrest Matchers did not work for me.

    See also this answer: https://stackoverflow.com/a/74195945/3824715