【问题标题】:Mock mvc expect exception模拟 mvc 期望异常
【发布时间】:2023-04-08 19:56:01
【问题描述】:

我有一个控制器和一些方法,它会抛出 CustomException:

@GetMapping
ResponseEntity<Void> getOriginalUrl() {
  ...
  throw new CustomException("my message");
  ...
}

我想测试一下。 测试:

 @Rule
 public ExpectedException thrown = ExpectedException.none();

 @Test
 public void testGetOriginalUrl() throws Exception {
 mvc.perform(get(...)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isNotFound());

    thrown.expect(CustomException.class);
    thrown.expectMessage("my message");
 }

但它不起作用。如何测试?

【问题讨论】:

    标签: java spring testing junit mocking


    【解决方案1】:

    即使您的任何异常服务器将返回500 内部服务器错误,所以您应该只验证状态码

     mvc.perform(get(...)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status()isInternalServerError())
            .andExpect(status().reason(containsString("my message")));
    

    【讨论】:

    • 是的,但我想检查异常类型和消息。
    • 可以查看消息但不能异常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多