Its my understanding that an efficient way to unit test a spring controller is too simply instantiate a new instance (of the required controller) and test the controller methods directly. Not bothering with Mock requests etc, as spring itself does need testing.
However, many of my controller methods simply return a view name as a single String, and I want to test that the model itself has the correct parameters and data.
Do I need to change the methods so that they return a ModelAndView, so that I can then access the model within the unit test ? Should my methods be doing that (returning a model and view) anyway ?
When I create a new ModelAndView within a controller method does the existing Model get overwritten ?
I’ll try to answer some of your questions.
About unit testing the controllers, sometimes I found that it’s needed to add Spring’s Mock request and response, as some spring features expect the request and response in the request context.
This is easy to figure out, because if they are not there, you’ll get a very specific error saying that the request or response are not in the context.
Related to the model, I found easier to return a ModelAndView and add some tests that check the output parameters and view name.
And I don’t know if the model gets overwritten.
This is my experience from a small project, so I’m by no means an expert, but I found this approach useful.