Both MockMvc and RestTemplate are used for integration tests with Spring and JUnit.
Question is: what's the difference between them and when we should choose one over another?
Here are just examples of both options:
//MockMVC example
mockMvc.perform(get("/api/users"))
.andExpect(status().isOk())
(...)
//RestTemplate example
ResponseEntity<User> entity = restTemplate.exchange("/api/users",
HttpMethod.GET,
new HttpEntity<String>(...),
User.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
With
MockMvc
, you're typically setting up a whole web application context and mocking the HTTP requests and responses. So, although a fakeDispatcherServlet
is up and running, simulating how your MVC stack will function, there are no real network connections made.With
RestTemplate
, you have to deploy an actual server instance to listen for the HTTP requests you send.It is possible to use both RestTemplate and MockMvc!
This is useful if you have a separate client where you already do the tedious mapping of Java objects to URLs and converting to and from Json, and you want to reuse that for your MockMVC tests.
Here is how to do it:
As said in this article you should use
MockMvc
when you want to test Server-side of application:for example:
And
RestTemplate
you should use when you want to test Rest Client-side application:example:
also read this example