2
我想在Spring Boot 1.4中执行单元测试来测试我的验证返回无效查询字符串参数400。Spring Boot 1.4单元测试休眠验证WebMvcTest
控制器
@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
}
}
异常处理程序
@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)");
}
}
语境
@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;
}
单元测试
@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));
}
}
然而,当我跑我的测试,我收到了200
不是400
。当我作为应用程序运行而不是作为测试时,验证不会执行。
我认为这可能是由于它在执行测试时没有拿起两个验证bean? 此验证工作
我试过这个,但后来我得到404s – ptimson