我正在使用MockMVC来测试我的控制器 .
我有以下控制器:
public class A{
...
@RequestMapping("/get")
public List<ADTO> get(@RequestParam(defaultValue = "15", required = false) Integer limit) throws IOException {
if(limit <= 0 || limit >= 50){
throw new IllegalArgumentException();
}
...
return aDTOs;
}
}
我目前的测试看起来像这样:
@Test
public void testGetAllLimit0() throws Exception {
mockMvc.perform(get("/A/get")
.param("limit","0")
)
.andDo(print())
.andExpect(...);
}
我用这个实例化MockMVC:
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
我怎样才能处理控制器中抛出的异常?
后来编辑:
我不确定最近我的代码中发生了什么,但它通过了测试:
@Test
public void testGetAllLimit0() throws Exception {
mockMvc.perform(get("/A/get")
.param("limit","0")
)
.andDo(print())
.andExpect(status().is(500));
}
如果我用 isOk()
替换 is(500)
,它仍会通过 . 这不好,我应该以某种方式检查该异常 .
如果我运行 gradle build
我得到这个:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException
1 回答
您是否尝试使用此处的自定义ExceptionHandler? :https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
如果这样做,您可以返回自定义HTTP响应代码并在测试中验证它们 .