Pete Pete - 1 year ago 184
Java Question

Integration Testing POSTing an entire object to Spring MVC controller

Is there a way to pass an entire form object on mock request when integration testing a spring mvc web app? All I can find is to pass each field separately as a param like this:


Which is fine for small forms. But what if my posted object gets larger? Also it makes the test code look nicer if I can just post an entire object.

Specifically I'd like to test the selection of multiple items by checkbox and then posting them. Of course I could just test posting a single item, but I was wondering..

We're using spring 3.2.2 with the spring-test-mvc included.

My Model for the form looks something like this:

NewObject {
List<Item> selection;

I've tried calls like this:

mockMvc.perform(post("/somehwere/new").requestAttr("newObject", newObject)

to a Controller like this:

@RequestMapping(value = "/somewhere/new")
public class SomewhereController {

@RequestMapping(method = RequestMethod.POST)
public String post(
@ModelAttribute("newObject") NewObject newObject) {
// ...

But the object will be empty (yes I've filled it before in the test)

The only working solution I found was using @SessionAttribute like this:
Integration Testing of Spring MVC Applications: Forms

But I dislike the idea of having to remember to call complete at the end of every controller where I need this. After all the form data does not have to be inside the session, I only need it for the one request.

So the only thing I can think of right now is to write some Util class that uses the MockHttpServletRequestBuilder to append all the object fields as .param using reflections or individually for each test case..

I don't know, feeld un-intuitive..

Any thoughts / ideas on how I might make my like easier? (Apart from just calling the controller directly)


Answer Source

One of the main purposes of integration testing with MockMvc is to verify that model objects are correclty populated with form data.

In order to do it you have to pass form data as they're passed from actual form (using .param()). If you use some automatic conversion from NewObject to from data, your test won't cover particular class of possible problems (modifications of NewObject incompatible with actual form).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download