在单元测试中模拟Spring Controller方法模型绑定

时间:2014-06-12 04:33:42

标签: java spring spring-mvc

在Spring Boot(Spring MVC)中,我试图根据this问题中的#4来测试表单与控制器的绑定。我无法复制神奇的帖子请求 - > spring将模型传递给控制器​​方法的模型对象绑定。这就是我到目前为止所做的:

WebRequest postRequest = new ServletWebRequest(new MockHttpServletRequest());
postRequest.setAttribute("itemModel.id", "23", RequestAttributes.SCOPE_REQUEST);
ItemModel itemModel = new ItemModel();
WebRequestDataBinder dataBinder = new WebRequestDataBinder(itemModel);
dataBinder.bind(postRequest);
assertThat(itemModel.getId(), equalTo(new Long(23)));

但是,我的断言失败,itemModel.getId()返回null。当我在@Controller类上调用方法时,如何像spring一样初始化模型?

更新

我已更新到以下内容,但仍然无效:

MockHttpServletRequest postRequest = new MockHttpServletRequest();
postRequest.addParameter("itemModel.id", "23");
WebRequest webPostRequest = new ServletWebRequest(postRequest);
ItemModel itemModel = new ItemModel();
WebRequestDataBinder dataBinder = new WebRequestDataBinder(itemModel);
dataBinder.bind(webPostRequest);
assertThat(itemModel.getId(), equalTo(new Long(23)));

2 个答案:

答案 0 :(得分:0)

如何使用HttpClient进行集成测试?看看这个例子,如果它对你有用:

      @Test
     public void test() {
             HttpClient loggedClient = new HttpClient();
             PostMethod loginPostMethod = new PostMethod(loginURL);
             loginPostMethod.addParameter("j_username", login);
             loginPostMethod.addParameter("j_password", password);
             loginPostMethod.addParameter("remember", "1");
             loginPostMethod.addParameter("clientType", clientType);
             loginPostMethod.addParameter("clientVersion", clientVersion);
              httpClient.executeMethod(postMethod);


             String USERS_URL = HTTP_SERVER_DOMAIN + "/service";
             PutMethod put = new PutMethod(USERS_URL);
             put.addRequestHeader("Content-Type", "application/json");
             put.setRequestBody("your_body");

             try {
                 loggedClient.executeMethod(put);
             } catch (HttpException e) {
                 e.printStackTrace();
             } catch (IOException e) {
                 e.printStackTrace();
             }

             assertEquals(HttpStatus.SC_OK, put.getStatusCode());

}

答案 1 :(得分:0)

我认为它应该只是“id”,而不是“itemModel.id”