I am trying to perform a unit test in Spring Boot 1.4 to test my validation returns a 400 on an invalid query string parameter.
Controller
@RestController
@Validated
public class ExampleController {
...
@RequestMapping(value = "/example", method = GET)
public Response getExample(
@RequestParam(value = "userId", required = true) @Valid @Pattern(regexp = MY_REGEX) String segmentsRequest {
// Stuff here
}
}
Exception Handler
@ControllerAdvice
@Component
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
// 400 - Bad Request
@ExceptionHandler(value = {ConstraintViolationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void constrainViolationHandle(HttpServletRequest request, ConstraintViolationException exception) {
logger.error("Error Bad Request (400)");
}
}
Context
@Bean
public Validator validator() {
final ValidatorFactory validatorFactory = Validation.byDefaultProvider()
.configure()
.parameterNameProvider(new ReflectionParameterNameProvider())
.buildValidatorFactory();
return validatorFactory.getValidator();
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
final MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
Unit Test
@RunWith(SpringRunner.class)
@WebMvcTest(ExampleController.class)
public class ExampleControllerTest {
private static final String EMPTY = "";
@Autowired
private MockMvc mvc;
@Test
public void test() throws Exception {
// Perform Request
ResultActions response = this.mvc.perform(
get("/example").param("userId", "invalid")
);
// Assert Result
response.andExpect(status().isBadRequest())
.andExpect(content().string(EMPTY));
}
}
However when I run my test I get a 200
not a 400
. The validation is not performed when I am running as an Application just not as a test.
I believe it may be due to it not picking up the two validation beans when performing the test? This validation works
Aucun commentaire:
Enregistrer un commentaire