如何在执行junit时将参数传递给Spring MVC控制器中的post方法? [英] How to pass parameters to post method in Spring MVC controller while doing junit?

查看:172
本文介绍了如何在执行junit时将参数传递给Spring MVC控制器中的post方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对我的Spring MVC控制器方法进行单元测试。下面是我尝试单元测试的方法,因为它在我启动服务器时工作正常。

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.

每当我点击 index 页面时,它会在我输入的浏览器上显示三个文本框数据并按下提交按钮,然后通过正确的值将呼叫转到 addNewServers

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


}

以下是我的junit课程:

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?

推荐答案

您只需要使用API​​:

You just need to use the API:

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

这篇关于如何在执行junit时将参数传递给Spring MVC控制器中的post方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆