spring 3.2 引入了 spring mvc 测试框架并将其作为官方的一部分,如文档中所述,我想用它来测试我的控制器,一种处理 post 请求的方法。
68 @RequestMapping(value = "/new", method = RequestMethod.POST)
69 public String addCarPost(@Valid @ModelAttribute NewCar car, BindingResult result){
70 if(result.hasErrors())
71 {
72 return "newcar" ;
73 }
74 carService.addCar(car) ;
75 return "redirect:/garage" ;
76 }
这是我的第一次尝试:
30 @RunWith(SpringJUnit4ClassRunner.class)
31 @ContextConfiguration("test-config.xml")
32 @WebAppConfiguration
33 public class GarageIntegrationTest {
// ....
72 @Test public void testAddCarPost() throws Exception{
// i didn't add any parameters to request.
73 this.mockMvc.perform(post("/garage/new"))
74 .andExpect(view().name("newcar")) ;
75 }
// ....
}
我想测试@Valid、@RequestMapping 和@ModelAttribute,我没有向请求添加任何参数,因此NewCar()
实例化了一个新类,该类的所有属性都初始化为null 或0,因此验证器必须检测到新实例有错误并返回视图“newcar”,当我运行这个测试时,我在服务中有一个 NullPointerException carService
,它的行为就像result.hasErrors()
已经返回false
,我错过了一些东西。