2

I'm developing an application using Spring 4.1.7 and I'm performing some unit tests using mockMvc with the standalone context configuration. I want to test a controller method where the form is submitted.

The problem is that some fields in the form are annotated with the custom validation annotation and ConstraintValidator responsible for the validation requires additional dependencies which I want to mock. How can I do it?

The code of the validator is provided below:

public class EmailValidator implements ConstraintValidator<CorrectEmail, Object> {

    @Autowired
    private ConfigurationManager configurationManager;

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        String pattern = configurationManager.getPattern();
        //performing checks
    }
}

Code of the test is provided below:

@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class RegisterPageControllerUnitTest {

    private MockMvc mockMvc;

    @InjectMocks
    private Controller controller;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void sdlkjf() throws Exception {
        mockMvc.perform(post("/register")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param("email", "email@gmail.com"));
}
}

When I try to run my test I get NullPointerException because configurationManager is not injected.

Roma Pochanin
  • 292
  • 2
  • 13
  • Possible duplicate of [Spring MockMVC - How to mock custom validators running outside of controllers](https://stackoverflow.com/questions/23161752/spring-mockmvc-how-to-mock-custom-validators-running-outside-of-controllers) – Arnaud Claudel Aug 15 '19 at 17:47
  • 1
    @ArnaudClaudel, no it isn't, SpringWebConstraintValidatorFactory was added in Spring 4.2.3. I've seen this question but unfortunately, it's of no use for me – Roma Pochanin Aug 15 '19 at 17:49
  • What is the `@InjectMocks` on `controller` supposed to do? I don't see you creating any mocks (`@Mock`) that are supposed to be injected into it. _(Note however I haven't quite understood the relation between `MockMvcBuilders.standaloneSetup` and `Mockito` yet. Apparently there is one but I haven't found a documentation on that ... )_ – second Aug 16 '19 at 00:39

0 Answers0