简体   繁体   English

MockMvc JsonPath结果匹配器不匹配单个值

[英]MockMvc JsonPath result matcher doesn't match single value

I am writing tests for my REST API controller and I need to check UUID value from returned JSON object, please see this test method: 我正在为我的REST API控制器编写测试,我需要检查返回的JSON对象中的UUID值,请参见此测试方法:

@Test
public void findById() throws Exception {

    final String uuidString = "6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1";
    final UUID id = UUID.fromString(uuidString);
    final Envelope envelope = createEnvelope(id);

    when(envelopeService.findOne(id, currentUser)).thenReturn(Optional.of(envelope));
    when(utilService.getLoggedInUser()).thenReturn(currentUser);

    mockMvc.perform(get("/api/envelopes/{id}", uuidString)).
            andExpect(status().isOk()).andExpect(content().contentType(Util.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$..id", is(uuidString)));

    verify(envelopeService, times(1)).findOne(id, currentUser);
    //verifyNoMoreInteractions(envelopeService);

}

but the test produces this error: 但测试产生此错误:

 Expected: is "6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1"
         but: was <["6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1"]>
        at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
        at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74)
        at org.springframework.test.web.servlet.result.JsonPathResultMatchers$1.match(JsonPathResultMatchers.java:86)
        at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)

It seems that ID 6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1 is returned correctly but is in serialized into different structure. 似乎ID 6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1正确返回,但是序列化为其他结构。

What is wrong with my code? 我的代码有什么问题?

As i see it, the jsonPath variable is an array of objects, not a single String. 如我所见,jsonPath变量是对象数组,而不是单个String。

You should use $[0] to get the first and only element in your case which is the UUID: 您应该使用$[0]来获取第一个也是唯一的元素,即UUID:

mockMvc.perform(get("/api/envelopes/{id}", uuidString)).
            andExpect(status().isOk())
            .andExpect(content().contentType(Util.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$[0]", is(uuidString))); 

The reason is your jsonpath declaration is wrong 原因是您的jsonpath声明错误

"6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1"  <--- String
<["6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1"]> <--- Array

you shouldn't use $..id , which give you an array back. 你不应该使用$..id ,它会给你一个数组。 checkout the document here https://github.com/jayway/JsonPath 在此处签出文档https://github.com/jayway/JsonPath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM