'How to unit test exception message thrown inside try and caught by catch using mockMvc
I have a controller somewhere like this:
@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");
}
}
I'm trying to test it like this:
@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();
}
The tests pass as it asserts the return piece from the catch block. However, I'm not seeing a way to assert which exception was thrown and what is the message inside it? (the line commented out fails the test when uncommented).
Thank you.
Solution 1:[1]
You cannot test for the Java exception in the traditional sense. You need to test for the response status, and body if you need to. MockMVC is mocking the HTTP request / response.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Thompson |
