LoginSignup
1
2

More than 5 years have passed since last update.

【Spring Boot】WebMVCのControllerでValidatorをバインドしてるとテストで「java.lang.IllegalStateException: Invalid target for Validator...」って言われる

Last updated at Posted at 2018-03-07

やってることは単純なのですが、うっかりはまってしまって一時間くらい悩んだのでメモしておきます。

環境

  • Windows10
  • java8
  • Spring boot 2.0.0.RELEASE

結論

こーんなコードがあって、そいつテストを書くぜ!というときに。

@Controller
@RequestMapping("/test/aaa")
public class SampleController{

    @Autowired
    SampleValidator validator;

    @InitBinder("sampleForm")
    public void validateBinder(WebDataBinder binder){
        binder.addValidators(validator);
    }

    @GetMapping("/")
    public String index(@ModelAttribute SampleForm form){
        // なんかしらの処理
        return "sample/form";
    }

}

こうやってかくとよい。

@RunWith(SpringRunner.class)
@WebMvcTest(SampleController.class)
@ContextConfiguration(classes = ApplicationTest.class)
public class SampleControllerTest{

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    SampleValidator validator;

    @Before
    public void before(){
        when(validator.supports(any())).thenReturn(true);
    }

    @Test
    public void test1(){
        // test
    }
}

補足

↑の例で before() の処理がないと

java.lang.IllegalStateException: Invalid target for Validator [xxx.SampleValidator#0 bean] : SampleForm(xxx)

みたいな例外が出てしまってテストが起動しません。

テスト実行時に(実態はMockになっている)SampleValidatorSampleForm に適用できるかどうかのチェック処理( SampleValidator#supports() )の戻りが null になっているのが原因だったようです。
なので、モックのふるまいとして常にOKを返すように定義したらちゃんと動作しましたよ、というメモでした。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2