5

I have a custom ConstraintValidator:

@Component
public class FooValidator implements ConstraintValidator<FooAnnotation, String> {

    @Inject
    private FooRepository fooRepository;

    @Override
    public void initialize(FooAnnotation foo) {
    }

    @Override
    public boolean isValid(String code, ConstraintValidatorContext context) {

        Foo foo = fooRepository.findByCode(code);
        //My code
    }
}

In my Junit tests and MockMVC I call the url but fooRepository bean validator is always null.

How I can inject it in my test controller? I tried to create a mock repository but it is also null. My source code test:

public class FooControllerTest {

    @InjectMocks
    private FooController fooController;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        // Process mock annotations
        MockitoAnnotations.initMocks(this);

        // Setup Spring test in standalone mode
        this.mockMvc = MockMvcBuilders.standaloneSetup(fooController)
                .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
                .build();
    }   

    @Test
    public void testSave() throws Exception {
        Foo foo = new Foo();
        // given
            //My code...
        // when
        // then

        // with errors
        this.mockMvc.perform(post("/foo/update")
                .param("name", "asdfasd")
                .sessionAttr("foo", foo))
                .andExpect(model().hasErrors())
                .andExpect(model().attributeHasFieldErrors("foo", "name"));
    }
}
oscar
  • 1,636
  • 6
  • 31
  • 59

1 Answers1

-2

You should add a @ContextConfiguration to your test, among other things.

aglavina
  • 375
  • 1
  • 5
  • 13
  • yes, this works for me. I use "@ContextConfiguration" and "@WebAppConfiguration". But this way test use the real context. I cant mock the services. I solve this load database from xml file this way "@DatabaseSetup("classpath:testData/ddbb.xml")" – oscar Jun 29 '16 at 06:55