如何测试POST Spring MVC

如何测试POST Spring MVC,第1张

如何测试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)  { }     }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5641692.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存