Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring's mockMvc, how do I check if the returned data contains part of a string?

Tags:

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

like image 643
Dave Avatar asked May 17 '16 18:05

Dave


People also ask

What is MockMVC in Junit?

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.


1 Answers

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 + "\"}")));  
like image 67
unigeek Avatar answered Sep 19 '22 19:09

unigeek