Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you possibly write test case for boolean in mockito, spring mvc environment

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(???);
like image 454
yas Avatar asked Jul 10 '14 16:07

yas


People also ask

Which class is used to test Spring MVC REST Web application?

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.

How do you write a unit test case for a controller in Java?

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 in spring?

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.


1 Answers

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

like image 158
geoand Avatar answered Sep 23 '22 20:09

geoand