如何使用mockMvc对try内部抛出并被catch捕获的异常消息进行单元测试



我有一个类似这样的控制器:

@GetMapping(value = "redirect")
public ModelAndView oauthRedirect() {
try {
if (true) {
serviceOAuthMetrics.addRedirectCookieException();
throw new AuthenticationChainException("User or client is null in state token");
}
return new ModelAndView(REDIRECT + redirectUrl + "closewindow.html?connected=true");
} catch (Exception e) {
return new ModelAndView(REDIRECT + redirectUrl + "closewindow.html?connected=false");
}
}

我试着这样测试:

@Test
void oauthRedirectThrowsExceptionUserIdIsNullTest() throws Exception {
RequestBuilder request = MockMvcRequestBuilders
.get("/oauth/redirect")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON);
mockMvc.perform(request)
.andExpect(redirectedUrl("http://localhost:8080/closewindow.html?connected=false"))
//.andExpect(content().string("AuthenticationChainException: User or client is null in state token"))
.andReturn();
}

测试在断言catch块的返回片段时通过。然而,我看不出有什么方法可以断言抛出了哪个异常,以及其中的消息是什么?(注释掉的行在取消注释时未通过测试(。

谢谢。

您无法测试传统意义上的Java异常。您需要测试响应状态,如果需要,还需要测试主体。MockMVC正在模拟HTTP请求/响应。

最新更新