Spring MVC单元测试-我可以将URL(带有参数)传递给控制器吗?
问题内容:
我将对Spring MVC控制器(或整个站点,如果可能)进行单元测试。
我想传递一个URL(作为字符串),例如“ / metrics / filter?a1 = 1&a2 = 2&a3 = abcdefg&wrongParam
= WRONG”,并检查返回哪个控制器。
有一个简单的方法吗?
例:
@RequestMapping(value = {"/filter"}, method = RequestMethod.GET)
@ResponseBody
public List<MetricType> getMetricTypes(
@RequestParam(value = "subject", required = false) Long subjectId
,@RequestParam(value = "area", required = false) Long areaId
,@RequestParam(value = "onlyImmediateChildren", required = false) Boolean onlyImmediateChildren
,@RequestParam(value = "componentGroup", required = false) Long componentGroupId
,@RequestParam(value = "hasComponentGroups", required = false) Boolean hasComponentGroups
) throws Exception
{
//some code
}
非常感谢
格言
更新
- 我只使用GET,不发布
- 我不使用模型对象(请参见上面的示例)
- 我的系统是一个Web服务,它具有许多带有各种参数组合的“ / someEntity / filter?a1 = 123&a2 = 1234&a3 = etc”方法。我不确定在这种情况下使用模型对象是否可行。
问题答案:
@RunWith( SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:WebRoot/WEB-INF/path/to/your-context.xml")
public class YourControllerTest {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private AnnotationMethodHandlerAdapter adapter;
@Before
public void setUp(){
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.adapter = new AnnotationMethodHandlerAdapter();
}
@Test
public void getMetricTypes() throws Exception{
request.setRequestURI("/filter");
request.setMethod("GET");
request.setParameter("subject", "subject");
request.setParameter("area", "area");
request.setParameter("onlyImmediateChildren", "onlyImmediateChildren");
request.setParameter("componentGroup", "componentGroup");
request.setParameter("hasComponentGroups", "hasComponentGroups");
ModelAndView mav = adapter.handle(request, response, yourController);
Assert.assertEquals(200, response.getStatus());
//Assert what you want
}
}