我有一个邮寄电话,运行这样的事情
assertThrows("Access Denied for non Blappity Roles",
() -> mvc.perform(post(url)
.content(requestStr)
.accept(ContentType.APPLICATION_JSON.toString())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(__ -> assertThat(__.getResolvedException(), CoreMatchers.instanceOf(AccessDeniedException.class))),
Matchers.instanceOf(AccessDeniedException.class))
我确实有一个这样定义的异常处理程序
@ExceptionHandler(AccessDeniedException.class)
public void accessDeniedException(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
e.printStackTrace(System.err);
log.error("Access Denied Exception {}", e.getClass(), e);
throw e;
无论如何,测试都会失败,并且 mockmvc 执行不会捕获 AccessDeniedException,并且测试失败......猜猜是什么,AccessDeniedException 逃脱了我的 Matcher。 我猜的是,我抛出的异常被某个地方的另一个过滤器吞噬了。无论如何我可以让 MockMvc 获得异常吗?
因为你从它的
AccessDeniedException
中重新抛出 @ExceptionHandler
,它被认为是未解决的异常,但 MockMvc
只会捕获已解决的异常。所以 AccessDeniedException
永远不会被解决,因此 getResolvedException()
是空的。
通常不需要重新抛出
@ExceptionHandler
的异常,只需配置在 HTTP 响应中应该回复什么 HTTP 状态码或响应体即可。
还假设你真的解决了
AccessDeniedException
,你不需要将 mockMvc.perform()
包裹在 assertThrows()
中。只需使用 mockMvc.perform().andExpect(xxx)
进行断言。