我将对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
}
非常感谢
马克西姆
已更新
答案 0 :(得分:3)
@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
}
}
答案 1 :(得分:0)
大多数人建议不要对请求映射进行集成测试 - 您可以对控制器pojo方法进行单元测试:即没有任何弹簧绑定。如果Spring正在运行,测试的重点是提出的论点。
因此在单元测试中调用控制器方法通常会将模型的实现作为参数传递(extendedmodelmap(?)。然后,测试代码可以检查添加到模型的内容以及返回值。
如果你真的想集成测试spring-mvc this article is good.
答案 2 :(得分:0)
测试Spring MVC控制器的一种新的更简单的方法是spring-test-mvc。