AKIWEB
AKIWEB

Reputation: 19612

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

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?

Upvotes: 2

Views: 8095

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

You just need to use the API:

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

Upvotes: 5

Related Questions