[英]Spring MVC unit tests - can I pass URL (with params) to controller?
我將對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
}
非常感謝
格言
更新
@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
}
}
大多數人建議不要集成測試請求映射 - 您可以對控制器pojo方法進行單元測試:即沒有任何彈簧綁定。 如果Spring正在運行,測試的重點是提出的論點。
因此在您的單元測試中調用控制器方法通常會將模型的實現作為參數傳遞(extendedmodelmap(?)。然后,測試代碼可以檢查添加到模型的內容以及返回值。
如果你真的想集成測試spring-mvc 這篇文章很好。
測試Spring MVC控制器的一種新的更簡單的方法是spring-test-mvc 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.