jsonpath - 在 Spring Boot 测试中将 JSON 中的对象与 jsonpath 匹配

标签 jsonpath spring-boot-test

我正在尝试使用 Spring Boot Test 为 rest 端点编写单元测试,但是当我尝试使用 jsonPath 对 json 响应中的对象进行断言时,即使在以下情况下也会抛出 AssertionError内容完全相同。

示例 Json

{
"status": 200,
"data": [
    {
        "id": 1,
        "placed_by": 1,
        "weight": 0.1,
        "weight_metric": "KG",
        "sent_on": null,
        "delivered_on": null,
        "status": "PLACED",
        "from": "1 string, string, string, string",
        "to": "1 string, string, string, string",
        "current_location": "1 string, string, string, string"
    }
]

Kotlin 中的代码

mockMvc.perform(
        get("/api/v1/stuff")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
    ).andExpect(status().isOk)
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
        .andExpect(jsonPath("\$.status").value(HttpStatus.OK.value()))
        .andExpect(jsonPath("\$.data.[0]").value(equalTo(stuffDTO.asJsonString())))

抛出 AssertionError 但值是相同的 Assertion Error Log

点击查看差异说

enter image description here

如何将 JSON 中的对象与 jsonPath 匹配?我需要能够匹配一个对象,因为该对象可以包含许多字段,单独匹配它们将是一个 PITA

最佳答案

我遇到了类似的问题,尽管在不知道您的 asJsonString 函数是什么的情况下很难说。另外我使用的是 Java,而不是 Kotlin。如果是同一个问题:

是因为jsonPath(expression)返回的不是字符串,所以匹配不上。您需要将 stuffDTO 转换为正确的类型以使用 JsonPath 进行匹配IE。在一个函数中,例如:

private <T> T asParsedJson(Object obj) throws JsonProcessingException {
    String json = new ObjectMapper().writeValueAsString(obj);
    return JsonPath.read(json, "$");
}

然后 .andExpect(jsonPath("\$.data.[0]").value(equalTo(asParsedJson(stuffDTO)))) 应该可以工作。

关于jsonpath - 在 Spring Boot 测试中将 JSON 中的对象与 jsonpath 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53514532/

相关文章:

java - JsonPathResultMatchers 不能应用于 ResultMatcher

Json 路径 - 对列表列表进行过滤

mysql - 在 SpringBoot 中,使用默认值注释字段的正确方法是什么

javascript - 可以根据 jsonpath 更新 json 的 JavaScript 库或模块是什么?

javascript - JSONPath 或其他类似 XPath 的 JSON/Javascript 实用程序;或 Jquery JSON

java - Spring WebTestClient JSON LocalDate 解码

java - 如何在 Spring Boot 测试中覆盖 application-test.yml ?

spring-boot - 对 Spring Boot Rest API 进行端到端测试的最佳方法是什么?

spring - 如何在 MockMvc 中从 jsonPath() 中检索字符串

java - 使用 JsonPath 提取非同质列表作为类型化对象