How can I possibly write test case for boolean in mockito, spring mvc environment
For e.g, like the following response
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"name":"myName","DOB":"12345"}
Forwarded URL = null
Redirected URL = null
Cookies = []
We would write the test case like,
mockMvc.perform(get("/reqMapping/methodName"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name",comparesEqualTo("myName");
.andExpect(jsonPath("$.DOB",comparesEqualTo("12345");
Right? But, when we got the response like follow
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
**Body = true**
Forwarded URL = null
Redirected URL = null
Cookies = []
How should I write the test case?
mockMvc.perform(get("/reqMapping/methodName"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(???);
We create the test data by using a test data builder class. Configure our mock object to return the created test data when its findAll() method is invoked.
Writing a Unit Test for REST Controller First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object.
What is MockMvc? MockMvc is a Spring Boot test tool class that lets you test controllers without needing to start an HTTP server. In these tests the application context is loaded and you can test the web layer as if i's receiving the requests from the HTTP server without the hustle of actually starting it.
All you need to do is the following:
mockMvc.perform(get("/reqMapping/methodName"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(content().string("true");
The meat of the above code the is the string
method of ContentResultMatchers
(returned by content()
).
Here is the relevant javadoc
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