开发者

Unit testing a spring 3 controller with methods that return only a view name

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.

class MyTest {
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @BeforeMethod(alwaysRun = true)
    public void setup() {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        controller = new Controller( /*inject dependencies here*/ );
    }
}

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.

public void shows_xxx_index_view {
    assertThat(modelAndView.getViewName(), equalTo("controller/index"));
}

public void model_contains_search_results {
    assertThat(modelAndView.getModelMap().get("searchResults"), equalTo(expected_results));
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜