10

我已经编写了一个测试并且它之前成功但现在我得到一个 AssertionError: No value for JSON Path。

@Test
public void testCreate() throws Exception {
    Wine wine = new Wine();
    wine.setName("Bordeaux");
    wine.setCost(BigDecimal.valueOf(10.55));

    new Expectations() {
        {
            wineService.create((WineDTO) any);
            result = wine;
        }
    };

    MockMultipartFile jsonFile = new MockMultipartFile("form", "", "application/json", "{\"name\":\"Bordeaux\", \"cost\": \"10.55\"}".getBytes());
    this.webClient.perform(MockMvcRequestBuilders.fileUpload("/wine").file(jsonFile))
            .andExpect(MockMvcResultMatchers.status().is(200))
            .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Bordeaux"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.cost").value(10.55));
}

我得到的错误是:

java.lang.AssertionError: No value for JSON path: $.name, exception: No results path for $['name']

我不明白它没有得到什么或缺少什么。

4

6 回答 6

8

您断言您的响应包含一个name带有 value的字段Bordeaux

您可以使用 打印您的回复this.webClient.perform(...).andDo(print())

于 2015-11-11T21:11:26.487 回答
7

我遇到了同样的问题。

解决方案 :

使用.andReturn().getResponse().getContentAsString();,您的响应将是一个字符串。我的回应是:

{"url":null,"status":200,"data":{"id":1,"contractName":"Test contract"}

当我尝试这样做.andExpect(jsonPath("$.id", is(1)));时出现错误:java.lang.AssertionError: No value for JSON path: $.id

为了修复它,我做了.andExpect(jsonPath("$.data.id", is(1)));并且它有效,因为 id 是数据中的一个字段。

于 2017-08-30T08:53:47.237 回答
3

最有可能 jsonPath 将文件的主体解释为列表,这应该可以解决问题(注意添加的方括号作为列表访问器):

.andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("Bordeaux"))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].cost").value(10.55));
于 2019-07-14T23:05:38.087 回答
1

我的返回正文是{'status': 'FINISHED', 'active':false} 并且 jsonPath 确实看到status了字段,但是看到了active. 解决方案:使用jsonPath("$.['status']")代替jsonPath("$.status")

我的假设:可能 jsonPath 忽略了一些关键字,如“状态”等......

于 2021-11-24T12:21:09.127 回答
0

jackson-dataformat-xml在向我的项目添加依赖项后,我遇到了同样的问题。

为了解决这个问题,我不得不改变我的响应实体:

return new ResponseEntity<>(body, HttpStatus.*STATUS*)

return ResponseEntity.*status*().contentType(MediaType.APPLICATION_JSON).body(*your body*).

这样它就可以正常工作,因为您已经直接将json身体的返回类型设置为。

于 2019-09-11T08:22:55.783 回答
-1

无论您要测试什么,都.name不再有一个属性被调用name,错误消息对该部分非常清楚。

java.lang.AssertionError: No value for JSON path: $.name, exception: No results path for $['name']

没有人知道你做了什么改变以使它从工作变为不工作你在问题中发布的任何内容都不能告诉我们。

于 2015-11-11T21:33:15.670 回答