REST Endpoint Testing With MockMvc

In this post, I'm going to show you how to test a Spring REST endpoint without a servlet container. In the past, integration tests were the only meaningful way to test a Spring REST endpoint. This involved spinning up a container like Tomcat or Jetty, deploying the application, calling the endpoint, running some assertions, and then stopping the container. While this is an effective way to test an endpoint, it isn't particularly fast. We're forced to wait while the entire application is stood up, just to test a single endpoint.

An alternative approach is to write vanilla unit tests for each REST controller, manually instantiating the Controller and mocking out any dependencies. These tests will run much faster than integration tests, but they're of limited value. The problem is, by manually creating the Controller outside of the Spring Application Context, the controller loses all the useful request/response handling that Spring takes care of on our behalf. Things like: