简体   繁体   English

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

[英]Simulate Spring Controller method model binding in unit test

In Spring Boot (Spring MVC) I am trying to test the binding of a form to a controller as per #4 in this question. 在Spring Boot(Spring MVC)中,我尝试按照问题中的#4测试表单与控制器的绑定。 I am having trouble replicating the magical post request -> model object binding that spring does to pass the model into the controller method. 我在复制Spring用来将模型传递到controller方法中的神奇的post请求->模型对象绑定时遇到麻烦。 This is what I have so far: 这是我到目前为止的内容:

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

However, my assertion fails and itemModel.getId() returns null. 但是,我的断言失败并且itemModel.getId()返回null。 How do I initialize the model like spring does when it calls the methods on my @Controller classes? 当调用@Controller类上的方法时,如何像spring一样初始化模型?

UPDATE 更新

I've updated to the following, but it's still not working: 我已经更新为以下内容,但仍无法正常使用:

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

What about use an Integration test using HttpClient?. 如何使用HttpClient进行集成测试? Look this example if it's useful for you: 如果对您有用,请看以下示例:

      @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());

} }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM