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


77

我正在使用Spring 3.2模拟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是否正确的方法

Answers:


108

当我分析您的代码。我也遇到过同样的问题,但是我的问题是,如果我同时提供名字和姓氏的值,则表示它工作正常。但是当我只给出一个值时,它表示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);
    }

我写了相同的代码,但是modelAttribute有问题。请阅读stackoverflow.com/questions/19427341/...
gstackoverflow

11
注意,print()是一种MockMvcResultHandlers上课方法
WildDev 2015年

8

如果有人来到这个问题,寻找能够在同一时间(我的情况),您可以使用添加多个参数.paramsMultivalueMap而不是增加每个.param

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

0

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

(我认为ModelAttribute是一种帮助程序,它将根据表单中的大量字段构造对象,但是您可能需要阅读一些内容以获得更好的定义)


在那不是问题之前,我使用了ModelAttribute。我对如何发送@RequestParam感到困惑
jackyesind 2013年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.