3

I'm using MockMvc to test my method that has a date parameter. The parameter is annotated with @DateValid but MockMvc doesn't trigger the validator and returns success when I input a wrong date.

StudentControler

public ResponseEntity<?> getStudents(@PathVariable("id") String studentId,
                                                               @RequestParam("birthDate") @DateValid String Date) {
        //do something
    }

Test

public class StudentController extends AbstractControllerTest {
      @Test
    public void testStudents_validRequest() throws Exception {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("birthDate","aaaa");
    
        MvcResult result = getMvc().perform(get("/student/{studentId}", "test")
                .params(params)
                .characterEncoding(StandardCharsets.UTF_8.name())
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().json(mapToJson(studentResDto)))
                .andReturn();

        verify(studentService).getStudentId(anyString(), anyString());
        log(log, result);
    }

}

I do not understand why because when I test using Postman it works as expected. Postman does validate but MockMvc does not? I using Spring-Boot 2.1.3

THelper
  • 15,333
  • 6
  • 64
  • 104
Tbtrungdn
  • 31
  • 4

1 Answers1

1

I can think of 2 problems here:

  1. The validation annotation class is not loaded properly in your test. This seems to happen primarily when combining Spring validation with Hibernate validation (see also this question on how to fix that.

  2. Your test is not setup properly. Could it be that you are not fully loading your controller in your mock test? Perhaps you are mocking the controller accidentally?

THelper
  • 15,333
  • 6
  • 64
  • 104