Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check JSON in response body with mockMvc

This is my method inside my controller which is annotated by @Controller

@RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")     @ResponseBody     public JSONObject getServerAlertFilters(@PathVariable String serverName) {         JSONObject json = new JSONObject();         List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, "");         JSONArray jsonArray = new JSONArray();         jsonArray.addAll(filteredAlerts);         json.put(SelfServiceConstants.DATA, jsonArray);         return json;     } 

I am expecting {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} as my json.

And this is my JUnit test:

@Test     public final void testAlertFilterView() {                try {                        MvcResult result = this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").session(session)                     .accept("application/json"))                     .andDo(print()).andReturn();             String content = result.getResponse().getContentAsString();             LOG.info(content);         } catch (Exception e) {             e.printStackTrace();         }     } 

Here is the console output:

MockHttpServletResponse:               Status = 406        Error message = null              Headers = {}         Content type = null                 Body =         Forwarded URL = null       Redirected URL = null              Cookies = [] 

Even result.getResponse().getContentAsString() is an empty string.

Can someone please suggest how to get my JSON in my JUnit test method so that I can complete my test case.

like image 796
Zeeshan Avatar asked May 27 '15 12:05

Zeeshan


2 Answers

I use TestNG for my unit testing. But in Spring Test Framework they both looks similar. So I believe your test be like below

@Test public void testAlertFilterView() throws Exception {     this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").             .andExpect(status().isOk())             .andExpect(content().json("{'data':[{'useRegEx':'false','hosts':'v2v2v2'}]}"));     } 

If you want check check json Key and value you can use jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

You might find thatcontent().json() are not solveble please add

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

like image 198
Menuka Ishan Avatar answered Sep 28 '22 03:09

Menuka Ishan


The 406 Not Acceptable status code means that Spring couldn't convert the object to json. You can either make your controller method return a String and do return json.toString(); or configure your own HandlerMethodReturnValueHandler. Check this similar question Returning JsonObject using @ResponseBody in SpringMVC

like image 27
medvedev1088 Avatar answered Sep 28 '22 02:09

medvedev1088