Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 226 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Spring's mockMvc, how do I check if the returned data contains part of a string?

#1
I’m using Spring 3.2.11.RELEASE and JUnit 4.11. Using the Spring mockMvc framework, how do I check if a method returning JSON data contains a particular JSON element? I have


mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andExpect(content().string("{\"id\":\"" + id + "\"}"));

but this checks for an exact match against the string returned and I’d rather check if the JSON string contains the value contained by my local field “id”.
Reply

#2
Looks like you can pass a Hamcrest Matcher instead of a string there. Should be something like:

mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andExpect(content().string(org.hamcrest.Matchers.containsString("{\"id\":\"" + id + "\"}")));

Reply

#3
Another way you can get to the String respone of a mockMVC requst so you can compare or manipulate it in other ways is as follows:

MvcResult result = mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andReturn();
String stringResult = result.getResponse().getContentAsString();
boolean doesContain = stringResult.contains("{\"id\":\"" + id + "\"}");

You could also wrap the whole thing in an assertTrue while still using String methods:

assertTrue(mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString()
.contains("{\"id\":\"" + id + "\"}");

I prefer the approved answer, just thought I would submit this as another alternative.
Reply

#4
A more appropriate way to do that is:

mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", org.hamcrest.Matchers.is(id)));
Reply

#5
I know it's been too many years, but still, I hope my answer can be useful for someone =)
When I need to check if a json value form a response contains some string I use `containsString` method:

mockMvc.perform(post("/url")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.andExpect(status().isOk())
.andExpect(jsonPath("$.field1").value(value1))
.andExpect(jsonPath("$.field2", containsString(value2)));

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through