Testing Spring MVC Controllers
Since Spring 3.2 (January, 2013), it is possible to test Spring MVC controllers without an external framework. The goal of this article is to show how to test Spring MVC controllers using only Spring testing capabilities.
To do so, a very simple Spring Boot project will be used as a support. You can find it on GitHub. The controller to test will first be introduced. Then, explanations will be given on how to test it.
The controller that will be tested is showed below. It permits to do a search in a fruit list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
The test class must be annotated with the following annotations:
@RunWith(SpringJUnit4ClassRunner.class)to benefit from Spring features in JUnit tests.
@SpringApplicationConfiguration(classes = DemoTestSpringMvcApplication.class)to specify the configuration class that will be used during the test.
@WebAppConfigurationto indicate that the Spring application context that must be loaded is a
The entry point used to perform the tests is the class
MockMvc. Thereafter, the usage of this class will be explained.
The set up of the
MockMvc class can be done as follows:
1 2 3 4 5
First, the controller must be instantiated (
1). Then, the mock is initialized using the static method
2). At this point, the mock is ready to test the controller.
MockMvc.perform() allows to simulate HTTP requests to the controller. For instance, a GET request is done as follows:
1 2 3 4
MockMvcRequestBuilders provides static methods, such as
post, to simulate HTTP requests on a particular endpoint of the controller (
1). HTTP parameters can be added fluently to the request (
Furthermore, other static methods are provided by the
- HTTP verbs like
fileUploadto upload binary files.
- Others (documentation).
MockMvc permits to add assertions to the controller’s response.
1 2 3 4 5
Assertions are done with the
andExpect() method. The class
MockMvcResultMatchers provides static methods to do assertions on the HTTP status (
1), the view asked by the controller (
2) and on the model completed by the controller (
The Spring test framework is a very powerful, complete and simple way to test Spring MVC controllers. Its fluent API allows to write elegant and yet precise tests.
Crafties réalise des audits de code, des formations, des accompagnements et des développements. Vous pouvez nous contacter à firstname.lastname@example.org pour tout besoin.