I am using jUnit 5 and Mockito to test my POST API. Here is what my method definition looks like.
public ResponseEntity<Object> fetch(@NotNull @ApiParam(value = "any" ,required=true) @Pattern(regexp="^[0-9]+$", message = "any") @RequestHeader(value="any", required=true) String any, @ApiParam(value = "any" ) @Valid @RequestBody SomeClass any);
My test method is
@Test
void fetchTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(URI)
.header("any", "abc")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(any)))
.andExpect(status().isBadRequest());
}
I have defined header regex to only accept numbers and not alphabets still its accepting "abc". The same thing works fine using postman i.e. it throws Bad request when requesting from postman.
Here is how I have initialised my MockMvc
this.mockMvc = MockMvcBuilders
.standaloneSetup(apiController)
.setControllerAdvice(new GlobalExceptionHandler())
.build();
MockMvc works fine if I send invalid request body (the @valid annotation works) but if I send invalid header it does not work (the @pattern annotation does not work)
Any suggestions would be helpful.