ドキュメントに記載されているように、spring 3.2 は spring mvc テスト フレームワークを導入し、それを公式の一部にしました。これを使用して、ポスト リクエストを処理するメソッドであるコントローラーをテストしたいと考えています。
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