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

Jan*_*ing 13 testing spring-boot spring-webflux spring-webclient

我们正在使用 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());
Run Code Online (Sandbox Code Playgroud)

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

java.lang.AssertionError:JSON 路径“$.data.movi​​e.id”没有值

...

引起原因:com.jayway.jsonpath.PathNotFoundException:路径 $['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);
Run Code Online (Sandbox Code Playgroud)

然后我看到的结果是

{"data":{"deleteMovie":{"id":7}}}
Run Code Online (Sandbox Code Playgroud)

我发现我期望的是“movie”而不是“deleteMovie”属性。所以我将测试更改为

.jsonPath("$.data.deleteMovie.id")
Run Code Online (Sandbox Code Playgroud)

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

有没有更好的方法让WebTestClient在测试失败时始终输出responseBody?

Jan*_*ing 30

到目前为止我发现的最好方法是添加

.expectBody()
.consumeWith(System.out::println)
Run Code Online (Sandbox Code Playgroud)

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