java 如何使用 mockmvc 处理控制器异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29587958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to treat controller exception with mockmvc
提问by tzortzik
I am using MockMVC to test my controller.
我正在使用 MockMVC 来测试我的控制器。
I have the following controller:
我有以下控制器:
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;
}
}
And my current test looks like this:
我目前的测试是这样的:
@Test
public void testGetAllLimit0() throws Exception {
mockMvc.perform(get("/A/get")
.param("limit","0")
)
.andDo(print())
.andExpect(...);
}
I am instantiating MockMVC with this:
我正在用这个实例化 MockMVC:
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
How can I take care of that exception thrown in my controller?
我该如何处理控制器中抛出的异常?
Later Edit:
后来编辑:
I'm not sure what happened in my code recently but it passes the test:
我不确定我的代码最近发生了什么,但它通过了测试:
@Test
public void testGetAllLimit0() throws Exception {
mockMvc.perform(get("/A/get")
.param("limit","0")
)
.andDo(print())
.andExpect(status().is(500));
}
It still passes if I replace is(500)
with isOk()
. And this is not good, I should check somehow for that exception.
如果我替换is(500)
为isOk()
. 这不好,我应该以某种方式检查该异常。
If I run a gradle build
I get this:
如果我运行一个gradle build
我得到这个:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException
采纳答案by mrkernelpanic
Did you try to use a custom ExceptionHandler like here? : https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
您是否尝试使用像这里这样的自定义 ExceptionHandler ?:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
If you do so you can return custom HTTP response codes and verify them in your test.
如果这样做,您可以返回自定义 HTTP 响应代码并在测试中验证它们。