我有一个 Controller 和一些方法,它会抛出 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");
}
但是它不起作用。我如何测试它?
最佳答案
即使您的任何异常服务器将返回500
内部服务器错误,所以您应该只验证状态代码
mvc.perform(get(...)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status()isInternalServerError())
.andExpect(status().reason(containsString("my message")));
关于java - 模拟 mvc 期望异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60534682/