Janning Vygen
Janning Vygen

Reputation: 9222

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

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?

Upvotes: 15

Views: 9464

Answers (1)

Janning Vygen
Janning Vygen

Reputation: 9222

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.

Upvotes: 33

Related Questions