首页 > 解决方案 > 春季启动中@ControllerAdvice的junit测试

问题描述

我正在尝试测试我RestController的验证。这是我的controller

@RequestMapping(value="/my-data",method=RequestMethod.GET, produces= {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<?> doSomething(@Validated @RequestParam (value = "id")@Size(min=6,max=6) String id){

    //some logic here
} 

我有一个ControllerAdvice要处理ConstraintViolationException

    @ExceptionHandler({ ConstraintViolationException.class })
    public ResponseEntity<?> handleConstraintViolation(ConstraintViolationException ex, WebRequest request) {

        //exception handling here
return  ResponseEntity.status(400).body("My error Message here");

    } 

万事皆安。但是现在我正在尝试编写单元测试用例,但我的单元测试用例永远不会抛出ConstraintViolationException

我设置MockMvc如下

mvc = MockMvcBuilders.standaloneSetup(myController).setControllerAdvice(new MyControllerAdviceClass()).build();

和测试用例为

@Test
public void testForConstrain() throws Exception {
    mvc.perform(get("/my-data")
            .param("id", "123"))
    .andExpect(status().isBadRequest());
}

但是这个测试用例没有通过,因为ConstraintViolationException没有抛出。不知道我在这里做错了什么。

标签: javajunitspring-batchspring-boot-test

解决方案


推荐阅读