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



我们正在使用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: JSON 路径 "$.data.movie.id" 处没有值

原因:com.jayway.jsonpath.PathNotFoundException: Missing 路径 $['数据']['电影'] 中的属性

错误消息是完全正确的。但是要实际查看此 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}}}

我看到我期望"电影"而不是"删除电影"属性。 所以我将我的测试更改为

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

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

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

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

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

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

最新更新