gpt4 book ai didi

java - Spring MVC 单元测试 - 我可以将 URL(带参数)传递给 Controller ​​吗?

转载 作者:行者123 更新时间:2023-11-29 06:01:19 25 4
gpt4 key购买 nike

我将对 Spring MVC Controller (或整个站点,如果可能)进行单元测试。

我想传递一个 URL(作为字符串),例如"/metrics/filter?a1=1&a2=2&a3=abcdefg&wrongParam=WRONG"并检查将返回什么 Controller 。

有什么简单的方法吗?

例子:

 @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,不使用 post
  • 我不使用模型对象(见上面的例子)
  • 我的系统是一个网络服务,它有很多“/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
}
}

关于java - Spring MVC 单元测试 - 我可以将 URL(带参数)传递给 Controller ​​吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9995807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com