【问题标题】:How to test POST spring mvc如何测试POST spring mvc
【发布时间】:2012-09-26 17:24:37
【问题描述】:

我的问题是如何调用它。我可以的

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;
}

【问题讨论】:

    标签: spring-mvc spring-3 spring-test spring-test-mvc


    【解决方案1】:

    请参阅下面的示例代码,该代码演示了使用 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) 
                {
    
                } 
        }
    }
    

    【讨论】:

    • 非常感谢。必须是json吗?我必须使用请求正文吗?
    • 它可以转换成你的控制器接受的任何类型。形成数据,获取字节并将其设置为请求。
    • 所以我可以做 request.setContent(o); ?
    • 您需要将 o 转换为控制器接受的消息类型之一。控制器接受的消息类型是什么?喜欢 JSON/XML 吗?
    • 如果你试图接受模型属性,控制器需要修改为 (@ModelAttribute("myobject") MyObject o, @PathVariable String value) 然后在单元测试中你可以设置 MyObject作为 request.setAttribute("myobject", o) 之类的参数。
    【解决方案2】:

    你需要使用RequestBody:

    @Requestmapping(value="/save/{value}", method=RequestMethod.POST)
    public void post(@RequestBody MyObject o, @PathVariable String value{
       objectService.save(o);
    }
    

    关于请求正文文档的一般信息:http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody

    【讨论】:

    • 好吧..也许..但假装我正在使用它。我如何对此进行单元测试?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2019-03-25
    • 2013-07-17
    • 2015-08-07
    相关资源
    最近更新 更多