大佬教程收集整理的这篇文章主要介绍了如何测试POST Spring MVC,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
请参阅下面的示例代码,该示例代码演示如何使用junit和spring-test对控制器进行单元测试。
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtIEsContextTestExecutionListener.class,
TransactionalTestExecutionListener.class })
@Transactional
@ContextConfiguration(locations = {
"classpath:rest.xml"
})
public class ControllerTest{
private MockhttpServletRequest request;
private MockhttpServletResponse response;
@autowired
private RequestMapPingHandlerAdapter handlerAdapter;
@autowired
private RequestMapPingHandlerMapPing handlerMapPing;
@Before
public voID setUp() throws Exception
{
this.request = new MockhttpServletRequest();
request.setContentType("application/Json");
this.response = new MockhttpServletResponse();
}
@Test
public voID testPost(){
request.setMethod("POST");
request.setRequestURI("/save/test"); //replace test with any value
final ModelAndVIEw mav;
Object handler;
try{
MyObject o = new MyObject();
//set values
//Assuming the controller consumes Json
ObjectMapper mapper = new ObjectMapper();
//set o converted as JsON to the request body
//request.setContent(mapper.writeValueAsstring(o).getBytes());
request.setAttribute("attribute_name", o); //in case you are trying to set a model attribute.
handler = handlerMapPing.getHandler(request).getHandler();
mav = handlerAdapter.handle(request, response, handler);
Assert.assertEquals(200, response.getStatus());
//Assert other conditions.
}
catch (Exception e)
{
}
}
}
我的问题是如何称呼它。我可以做
MyObject o = new MyObject();
myController.save(o,"value");
但这不是我想做的。我希望MyObject出现在请求后的正文中吗?如何才能做到这一点?
@Requestmapping(value="/save/{value}",method=RequestMethod.POST)
public void post(@Valid MyObject o,@PathVariable String value{
objectService.save(o);
}
为了清楚起见,我在谈论单元测试。
编辑:
@RequestMapping(value = "/",method = RequestMethod.POST)
public View postUser(ModelMap data,@Valid Profile profile,BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return dummyDataView;
}
data.put(DummyDataView.DATA_TO_SEND,"users/user-1.json");
profileService.save(profile);
return dummyDataView;
}
以上是大佬教程为你收集整理的如何测试POST Spring MVC全部内容,希望文章能够帮你解决如何测试POST Spring MVC所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。