在Spring Boot Test中将JSON中的对象与jsonpath匹配 [英] Matching object in JSON with jsonpath in Spring Boot Test

查看:202
本文介绍了在Spring Boot Test中将JSON中的对象与jsonpath匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Spring Boot Test来为其余端点编写单元测试,但进展顺利,但是当我尝试使用jsonPath在json响应中的对象上断言时,即使内容相同且一样.

I'm trying to write unit tests for a rest endpoint with Spring Boot Test that's going well but when I try to assert on an object in the json response with jsonPath an AssertionError is thrown even when contents are identical and the same.

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"
    }
]

}

科特林语中的代码

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,但值相同

That throws AssertionError but the values are the same

点击查看差异说

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

How can I match an object in JSON with jsonPath? I need to be able to match an object because the object can contain many fields and it will be a PITA to match them individually

推荐答案

我遇到了类似的问题,尽管不知道您的asJsonString函数是什么很难说.我也使用Java,而不是Kotlin.如果是相同的问题:

I came across what looks like the same issue, though it's hard to say without knowing what your asJsonString function is. Also I was using Java, not Kotlin. If it is the same issue:

这是由于jsonPath(expression)没有返回字符串,因此将其与一个字符串匹配不起作用.您需要使用 JsonPath stuffDTO转换为正确的类型以进行匹配.在这样的功能中:

It's due to jsonPath(expression) not returning a string, so matching it with one doesn't work. You need to convert stuffDTO into the correct type for matching using JsonPath ie. in a function such as:

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))))应该可以工作.

这篇关于在Spring Boot Test中将JSON中的对象与jsonpath匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆