模拟MVC - 添加请求参数进行测试

时间:2013-07-31 13:55:50

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

我使用spring 3.2 mock mvc来测试我的控制器。我的代码是

 @Autowired
    private Client client;

     @RequestMapping(value = "/user", method = RequestMethod.GET)
        public String initUserSearchForm(ModelMap modelMap) {
            User user = new User();
            modelMap.addAttribute("User", user);
            return "user";
        }

        @RequestMapping(value = "/byName", method = RequestMethod.GET)
        @ResponseStatus(HttpStatus.OK)
        public
        @ResponseBody
        String getUserByName(@RequestParam("firstName") String firstName,
                                 @RequestParam("lastName") String lastName, @ModelAttribute("userClientObject") UserClient userClient) {

            return client.getUserByName(userClient, firstName, lastName);
        }

我写了以下测试:

@Test
 public void testGetUserByName() throws Exception {
        String firstName = "Jack";
        String lastName = "s";       
        this.userClientObject = client.createClient();
        mockMvc.perform(get("/byName")
                .sessionAttr("userClientObject", this.userClientObject)
                .param("firstName", firstName)
                .param("lastName", lastName)               
        ).andExpect(status().isOk())
                .andExpect(content().contentType("application/json"))
                .andExpect(jsonPath("$[0].id").exists())
                .andExpect(jsonPath("$[0].fn").value("Marge"));

}

我得到的是

java.lang.AssertionError: Status expected:<200> but was:<400>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:546)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)

为什么会这样?是通过@RequestParam

的正确方法

3 个答案:

答案 0 :(得分:79)

当我分析你的代码时。我也面临同样的问题,但我的问题是,如果我给名字和姓氏都有价值意味着它工作正常。但是,当我只给出一个值意味着它说400.无论如何使用.andDo(print())方法来找出错误

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

如果您的问题是org.springframework.web.bind.missingservletrequestparameterexception,则必须将代码更改为

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(@RequestParam( value="firstName",required = false) String firstName,
                             @RequestParam(value="lastName",required = false) String lastName, @ModelAttribute("userClientObject") UserClient userClient) {

        return client.getUserByName(userClient, firstName, lastName);
    }

答案 1 :(得分:1)

如果有人遇到这个问题,想同时添加多个参数(我的情况),则可以将.params MultivalueMap 结合使用,而不必添加每个{{1 }}:

.param

答案 2 :(得分:0)

@ModelAttribute是请求参数到特定对象类型的Spring映射。因此,您的参数可能看起来像userClient.usernameuserClient.firstName等,因为MockMvc模仿来自浏览器的请求,您需要传入Spring将从表单中使用的参数来实际构建{ {1}}对象。

(我认为ModelAttribute是一种帮助,可以从一堆表格中构建一个对象,但是你可能想要做一些阅读以获得更好的定义)