如何使用mockmvc处理控制器异常

tzo*_*zik 10 java spring mockmvc

我正在使用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;
    }

}
Run Code Online (Sandbox Code Playgroud)

我目前的测试看起来像这样:

@Test
public void testGetAllLimit0() throws Exception {
    mockMvc.perform(get("/A/get")
            .param("limit","0")
            )
            .andDo(print())
            .andExpect(...);
}
Run Code Online (Sandbox Code Playgroud)

我用这个实例化MockMVC:

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能处理控制器中抛出的异常?

后来编辑:

我不确定最近我的代码中发生了什么,但它通过了测试:

@Test
public void testGetAllLimit0() throws Exception {
    mockMvc.perform(get("/A/get")
            .param("limit","0")
            )
            .andDo(print())
            .andExpect(status().is(500));
}
Run Code Online (Sandbox Code Playgroud)

如果我取代它仍然通过is(500)使用isOk().这不好,我应该以某种方式检查该异常.

如果我跑了,gradle build我得到这个:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException
Run Code Online (Sandbox Code Playgroud)

mrk*_*nic 7

您是否尝试使用此处的自定义ExceptionHandler?:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

如果这样做,您可以返回自定义HTTP响应代码并在测试中验证它们.