Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC controller Test - print the result JSON String

Hi I have a Spring mvc controller

@RequestMapping(value = "/jobsdetails/{userId}", method = RequestMethod.GET) @ResponseBody public List<Jobs> jobsDetails(@PathVariable Integer userId,HttpServletResponse response) throws IOException {     try {                Map<String, Object> queryParams=new LinkedHashMap<String, Object>();           queryParams.put("userId", userId);          jobs=jobsService.findByNamedQuery("findJobsByUserId", queryParams);      } catch(Exception e) {         logger.debug(e.getMessage());         response.sendError(HttpServletResponse.SC_BAD_REQUEST);     }     return jobs; } 

I want to see how the JSON String will looks like when I run this. I wrote this test case

@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration("classpath:webapptest") @ContextConfiguration(locations = {"classpath:test-applicationcontext.xml"}) public class FindJobsControllerTest { private MockMvc springMvc;      @Autowired     WebApplicationContext wContext;      @Before     public void init() throws Exception {         springMvc = MockMvcBuilders.webAppContextSetup(wContext).build();     }      @Test     public void documentsPollingTest() throws Exception {         ResultActions resultActions = springMvc.perform(MockMvcRequestBuilders.get("/jobsdetails/2").accept(MediaType.APPLICATION_JSON));          System.out.println(/* Print the JSON String */); //How ?     } } 

How to get the JSON string?

I am using Spring 3, codehause Jackson 1.8.4

like image 763
iCode Avatar asked Feb 01 '14 07:02

iCode


People also ask

What is the @RequestMapping annotation used for?

RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods.

What is MvcResult?

public interface MvcResult. Provides access to the result of an executed request.


1 Answers

Try this code:

resultActions.andDo(MockMvcResultHandlers.print()); 
like image 150
JB Nizet Avatar answered Oct 02 '22 02:10

JB Nizet