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”.
MockMVC class is part of Spring MVC test framework which helps in testing the controllers explicitly starting a Servlet container. In this MockMVC tutorial, we will use it along with Spring boot's WebMvcTest class to execute Junit testcases which tests REST controller methods written for Spring boot 2 hateoas example.
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 + "\"}")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With