在 Spring 4 MVC 单元测试例子 一文中利用Spring test 框架进行了简单的测试,代码mockMvc.perform(get("/SayHello/getAnswer"))
使用get()
方法发送了一个GET请求。
现在需求变了,需要提交一个表单,该如何实现?
首先,要测试下面这样一个方法:
@Controller
@RequestMapping("/user")
public class UserController {@RequestMapping(method = RequestMethod.POST)@ResponseStatus( HttpStatus.CREATED )public void addUser(@Validated User user,BindingResult result,HttpServletResponse response) throws BindException{//省去代码}}
注意它要接收一个User类对象作为参数,User类如下:
@Component
public class User {private long id;private String name;//省去getter和setter
}
模拟请求中要如何携带这样的参数呢?是创建一个User对象,添加到请求中吗?实际,测试类应该这样编写:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:spring-servlet.xml","classpath:applicationContext.xml"})
public class UserControllerTest {@Autowiredprivate WebApplicationContext wac;private MockMvc mockMvc;@Beforepublic void Setup(){this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();}@Testpublic void testAddUser() throws Exception { mockMvc.perform(post("/user").param("id", "1")) //注意这行.andDo(print()).andExpect(status().is(201)).andExpect(redirectedUrl("/user/1"));}}
从上面的代码中可以看出,post()
方法可以像post("/user").param("id", "1")
这样加入表单参数,要加多个参数,post()
方法后面就可以加多个param()
方法。只要param()
方法添加的参数的名字和User类的属性名字相同即可。
这里使用的Spring框架版本号是4.2.4,3.x版本的测试可能与这个有所差别。
国外有网友也有遇到同样的问题,贴出实例代码,可以参看:Set @ModelAttribute in MockHttpServletRequest in JUnit Test