【问题标题】:How to unit test exception message thrown inside try and caught by catch using mockMvc如何对try中抛出的异常消息进行单元测试并使用mockMvc通过catch捕获
【发布时间】:2022-02-02 09:45:58
【问题描述】:

我有一个这样的控制器:

@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 spring-boot unit-testing assertion mockmvc


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2018-06-05
      相关资源
      最近更新 更多