你如何在 spring rest 控制器中测试异常?
How do you test exception in spring rest controller?
我正在尝试测试我的休息控制器是否抛出了异常。这是我的休息控制器:
@DeleteMapping
public ResponseEntity<Void> cancel(@RequestParam long id) {
if(id < 1) {
throw new MyException();
}
try {
doSomething();
}
catch (SomeException e) {
throw new MyException();
}
}
这是我的测试:
private MockMvc mockMvc;
@BeforeMethod
public void beforeMethod() {
initMocks(this);
mockMvc = standaloneSetup(new StudyDispatcherController(studyDispatcherService)).build();
}
@Test (expectedExceptions = MyException.class)
public void cancelWithInvalidParam() throws Exception {
mockMvc.perform(delete(BASE_URL).param("id", "-1").contentType("application/json").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest());
@Test (expectedExceptions = MyException.class)
public void cancelWithException() throws Exception {
doThrow(SomeException.class).when(myService).doSomething();
mockMvc.perform(delete(BASE_URL).param("id", "123").contentType("application/json").accept(MediaType.APPLICATION_JSON)).andExpect(status().is5xxServerError());
}
但是,它抛出
org.springframework.web.util.NestedServletException:请求处理失败;
我该如何正确处理这个问题?
你能试试下面的代码而不是 cancelWithInvalidParam() 方法吗
@Test (expectedExceptions = Exception.class)
public void cancelWithInvalidParam() throws Exception {
mockMvc.perform(delete(BASE_URL).param("id", "-1").contentType("application/json").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest());
我正在尝试测试我的休息控制器是否抛出了异常。这是我的休息控制器:
@DeleteMapping
public ResponseEntity<Void> cancel(@RequestParam long id) {
if(id < 1) {
throw new MyException();
}
try {
doSomething();
}
catch (SomeException e) {
throw new MyException();
}
}
这是我的测试:
private MockMvc mockMvc;
@BeforeMethod
public void beforeMethod() {
initMocks(this);
mockMvc = standaloneSetup(new StudyDispatcherController(studyDispatcherService)).build();
}
@Test (expectedExceptions = MyException.class)
public void cancelWithInvalidParam() throws Exception {
mockMvc.perform(delete(BASE_URL).param("id", "-1").contentType("application/json").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest());
@Test (expectedExceptions = MyException.class)
public void cancelWithException() throws Exception {
doThrow(SomeException.class).when(myService).doSomething();
mockMvc.perform(delete(BASE_URL).param("id", "123").contentType("application/json").accept(MediaType.APPLICATION_JSON)).andExpect(status().is5xxServerError());
}
但是,它抛出 org.springframework.web.util.NestedServletException:请求处理失败;
我该如何正确处理这个问题?
你能试试下面的代码而不是 cancelWithInvalidParam() 方法吗
@Test (expectedExceptions = Exception.class)
public void cancelWithInvalidParam() throws Exception {
mockMvc.perform(delete(BASE_URL).param("id", "-1").contentType("application/json").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest());