Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot properly test ErrorController Spring Boot

due to this tutorial - https://www.baeldung.com/spring-boot-custom-error-page I wanted to customize my error page ie. when someone go to www.myweb.com/blablablalb3 I want to return page with text "wrong url request". All works fine:

@Controller
public class ApiServerErrorController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "error";
    }

    @RequestMapping("/error")
    public String handleError() {
        return "forward:/error-page.html";
    }
}

But I dont know how to test it:

@Test
    public void makeRandomRequest__shouldReturnErrorPage() throws Exception {
        this.mockMvc.perform(get(RANDOM_URL))
                .andDo(print());

    }

print() returns:

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {X-Application-Context=[application:integration:-1]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

So I cant created something like this:

.andExpect(forwardedUrl("error-page"));

because it fails, but on manual tests error-page is returned.

like image 286
Adrian Avatar asked Jan 01 '26 22:01

Adrian


1 Answers

Testing of a custom ErrorController with MockMvc is unfortunately not supported.

For a detailed explanation, see the official recommendation from the Spring Boot team (source).

To be sure that any error handling is working fully, it's necessary to involve the servlet container in that testing as it's responsible for error page registration etc. Even if MockMvc itself or a Boot enhancement to MockMvc allowed forwarding to an error page, you'd be testing the testing infrastructure not the real-world scenario that you're actually interested in.

Our recommendation for tests that want to be sure that error handling is working correctly, is to use an embedded container and test with WebTestClient, RestAssured, or TestRestTemplate.

like image 162
Sam Brannen Avatar answered Jan 03 '26 13:01

Sam Brannen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!