Spring WebClient and jsonPath - How to output json result if test fails
Asked Answered
P

1

15

We are testing with WebTestClient (SpringBoot) our GraphQL Backend and have problems to see why exactly the test failed. Our code looks like this:

webTestClient
   .post().uri(GQLKonstanten.URL)
   .body(GQLRequestInserter.from(movieDeleteGQL, variables))
   .exchange()
   .expectBody()
   .jsonPath("$.errors").doesNotExist()
   .jsonPath("$.data.movie.id")
   .isEqualTo(movie.getId());

What I get is a stacktrace with the following message:

java.lang.AssertionError: No value at JSON path "$.data.movie.id"

...

Caused by: com.jayway.jsonpath.PathNotFoundException: Missing property in path $['data']['movie']

The error message is completely correct. But to actually SEE what this graphQl Exceution actually command returned I always change the WebClient execution into:

String responseBody = webTestClient
  .post().uri(GQLKonstanten.URL)
  .body(GQLRequestInserter.from(deleteMovieGQL, variables))
  .exchange()
  .expectStatus()
  .isOk()
  .expectBody(String.class)
  .returnResult().getResponseBody();
System.out.print(responseBody);

Then I see the result as

{"data":{"deleteMovie":{"id":7}}}

and I see that I expected "movie" instead of "deleteMovie" property. so I change my test to

.jsonPath("$.data.deleteMovie.id")

Always running the test twice and changing the code is cumbersome.

Is there a better way to let WebTestClient always output the responseBody when the test fails?

Pollaiuolo answered 17/1, 2020 at 14:58 Comment(2)
have you tested to just use the .log() function?Vesuvianite
I don't know what log function do you mean. I found a better way with .consumeWith(System.out::println) after expectBody()Pollaiuolo
P
33

Best way I found so far is to add a

.expectBody()
.consumeWith(System.out::println)

It prints out the json result always and not on error only. But it works for me.

Pollaiuolo answered 22/1, 2020 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.