2

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:

@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.

What is wrong with my code?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
jnemecz
  • 3,171
  • 8
  • 41
  • 77

2 Answers2

1

As i see it, the jsonPath variable is an array of objects, not a single String.

You should use $[0] to get the first and only element in your case which is the UUID:

mockMvc.perform(get("/api/envelopes/{id}", uuidString)).
            andExpect(status().isOk())
            .andExpect(content().contentType(Util.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$[0]", is(uuidString))); 
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
0

The reason is your jsonpath declaration is wrong

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

you shouldn't use $..id, which give you an array back. checkout the document here https://github.com/jayway/JsonPath

Jaiwo99
  • 9,687
  • 3
  • 36
  • 53