java – MockMVC如何在同一测试用例中测试异常和响应代码

前端之家收集整理的这篇文章主要介绍了java – MockMVC如何在同一测试用例中测试异常和响应代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想声明引发异常并且服务器返回500内部服务器错误.

要突出显示意图,请提供代码段:

  1. thrown.expect(NestedServletException.class);
  2. this.mockMvc.perform(post("/account")
  3. .contentType(MediaType.APPLICATION_JSON)
  4. .content(requestString))
  5. .andExpect(status().isInternalServerError());

当然,如果我写了isInternalServerError或isOk,那也没关系.
无论是否在throw.except语句下面抛出异常,测试都将通过.

你会怎么解决这个问题?

最佳答案
您可以尝试以下方式 –

>创建自定义匹配器

  1. public class CustomExceptionMatcher extends
  2. TypeSafeMatcher自定义匹配器

  3. exception.expect(CustomException.class);
  4. exception.expect(CustomException
  5.         .assertSomeThing("Some assertion text"));
  6. this.mockMvc.perform(post("/account")
  7.     .contentType(MediaType.APPLICATION_JSON)
  8.     .content(requestString))
  9.     .andExpect(status().isInternalServerError());
  10. P.S.:我提供了一个通用的伪代码,您可以根据自己的要求进行自定义.

猜你在找的Spring相关文章