java - 春季启动中@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
没有抛出。不知道我在这里做错了什么。
解决方案
推荐阅读
- php - 如何从父目录的子目录取消链接文件?PHP
- python - 我的 Python 代码中的某个地方有问题.. 我找不到它在哪里
- amazon-web-services - 在 AWS 上使用 Firebase Cloud Messaging (FCM) 发送通知时是否需要使用 Amazon SNS?
- android - 如何在开机时开启或启用 BT 和 Wifi?
- python-3.x - 在 Python3 中交错多个可变长度列表
- ios - iPhone BLE/GATT 接口
- java - 如何为相互 SSL 覆盖 Spring Boot 密钥库/信任库
- c++ - 使用 avro::memoryInputStream 创建 avro::DataFileReader
- swift - 将函数包装在闭包中以将其作为参数传递是否有任何开销
- javascript - 如何访问异步等待返回对象中的属性