Mock controller with an object parameter

Alex2330 picture Alex2330 · Oct 10, 2014 · Viewed 8.1k times · Source

I'm trying to test a method with this signature:

@RequestMapping(value="/Employee/{id}", method=RequestMethod.PUT, consumes="application/json") 
@Transactional
public @ResponseBody Map update(@PathVariable Integer id, 
    @RequestBody HashMap<String, Object> information) {

}

The problem is that MockMvc param attributes accept only String parameters, is there a way to pass a HashMap or an instance class object to the RequestBody as parameter?

When I try to pass a HashMap as a string, I get a MismatchException.

Answer

luboskrnac picture luboskrnac · Oct 10, 2014

You need to use Jackson for this. The idea is to deserialize your objects (doesn't matter that it's HashMap) into JSON string and pass it into MockMvc.

Here is tutorial how to do that. Just search for TestClass there and take a look how it is used. Skip the unit testing of GET requests.