How to pass parameters to post method in Spring MVC controller while doing junit?

孤人 提交于 2019-12-22 18:37:40

问题


I am doing unit testing on my Spring MVC controller methods. Below is my method which I am trying to unit test as it is working fine when I start my server.

Whenever I will be hitting index page it will show me three text box on the browser in which I am typing the data and pressing the submit button and then the call goes to addNewServers with the proper values.

Now I need to unit test the same thing:

@RequestMapping(value = "/index", method = RequestMethod.GET)
public Map<String, String> addNewServer() {
    final Map<String, String> model = new LinkedHashMap<String, String>();
    return model;
}

@RequestMapping(value = "/index", method = RequestMethod.POST)
public Map<String, String> addNewServers(@RequestParam String[] servers, @RequestParam String[] address,
    @RequestParam String[] names) {     


}

Below is my junit class:

private MockMvc mockMvc;

@Before
public void setup() throws Exception {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");

    this.mockMvc = standaloneSetup(new Controller()).setViewResolvers(viewResolver).build();
}

@Test
public void test04_newServers() throws Exception {

    String[] servers = {"3", "3", "3"};
    String[] ipaddress = {"10,20,30", "40,50,60", "70,80,90"};
    String[] hostnames = {"a,b,c", "d,e,f", "g,h,i"};


    // not sure how would I pass these values to my `addNewServers` method
    // which is a post method call.

}

Can anyone help me with this?


回答1:


You just need to use the API:

mockMvc.perform(post("/index").param("servers", servers)
                              .param("address", ipaddress)
                              .param("names", hostnames))


来源:https://stackoverflow.com/questions/22184566/how-to-pass-parameters-to-post-method-in-spring-mvc-controller-while-doing-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!