如何测试POST的Spring MVC(How to test POST spring mvc)

2019-07-31 23:46发布

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

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

Answer 1:

见下面的代码示例,演示单元测试使用JUnit和弹簧测试控制器。

@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) 
            {

            } 
    }
}


Answer 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



文章来源: How to test POST spring mvc