Spring WebClient 和 jsonPath - 如果测试失败如何输出 json 结果

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

我们正在使用 WebTestClient (SpringBoot) 测试我们的 GraphQL 后端,但在查看测试失败的确切原因时遇到了问题。我们的代码如下所示:

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

我得到的是带有以下消息的堆栈跟踪:

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

...

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

错误信息完全正确。但是为了实际查看此 graphQl Exceution 命令实际返回的内容,我总是将 WebClient 执行更改为:

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

然后我看到的结果是

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

我看到我期望 "movie" 而不是 "deleteMovie" 属性。所以我将测试更改为

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

总是运行测试两次,改代码很麻烦。

有没有更好的办法让WebTestClient在测试失败的时候一直输出responseBody?

到目前为止我发现的最佳方法是添加一个

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

它总是打印出 json 结果,而不仅仅是在出错时。但这对我有用。