Course – LS (cat=HTTP Client-Side)

Get started with Spring and Spring Boot, through the Learn Spring course:


1. Introduction

We frequently find ourselves with applications that perform some sort of web request. When it comes to testing this behavior, we have a few options with Spring apps.

In this quick tutorial, we’ll look at just a couple of ways of mocking such calls performed only through a RestTemplate.

We’ll start by testing with Mockito, a popular mocking library. Then we’ll use Spring Test, which provides us with a mechanism to create a mock server to define the server interactions.

2. Using Mockito

We can use Mockito to mock the RestTemplate altogether. With this approach, testing our service would be as simple as any other test involving mocking.

Let’s assume we have a simple EmployeeService class, which fetches employee details through HTTP:

public class EmployeeService {
    private RestTemplate restTemplate;

    public Employee getEmployee(String id) {
	ResponseEntity resp = 
          restTemplate.getForEntity("http://localhost:8080/employee/" + id, Employee.class);
	return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;

Now let’s implement our test for the previous code:

public class EmployeeServiceTest {

    private RestTemplate restTemplate;

    private EmployeeService empService = new EmployeeService();

    public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() {
        Employee emp = new Employee(“E001”, "Eric Simmons");
            "http://localhost:8080/employee/E001", Employee.class))
          .thenReturn(new ResponseEntity(emp, HttpStatus.OK));

        Employee employee = empService.getEmployee(id);
        Assertions.assertEquals(emp, employee);

In the above JUnit test class, we first asked Mockito to create a dummy RestTemplate instance using the @Mock annotation.

Then we annotated the EmployeeService instance with @InjectMocks to inject the dummy instance into it.

Finally, in the test method, we defined the behavior of our mock using Mockito’s when/then support.

3. Using Spring Test

The Spring Test module includes a mock server named MockRestServiceServer. With this approach, we configure the server to return a particular object when a specific request is dispatched through our RestTemplate instance. In addition, we can verify() on that server instance whether or not all expectations have been met.

MockRestServiceServer actually works by intercepting the HTTP API calls using a MockClientHttpRequestFactory. Based on our configuration, it creates a list of expected requests and corresponding responses. When the RestTemplate instance calls the API, it looks up the request in its list of expectations, and returns the corresponding response.

Thus, it eliminates the need of running an HTTP server in any other port for sending mock responses.

Let’s create a simple test for the same getEmployee() example using MockRestServiceServer:

@SpringBootTest(classes = SpringTestConfig.class)
public class EmployeeServiceMockRestServiceServerUnitTest {

    private EmployeeService empService;
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;
    private ObjectMapper mapper = new ObjectMapper();

    public void init() {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    public void givenMockingIsDoneByMockRestServiceServer_whenGetIsCalled_thenReturnsMockedObject()() {   
        Employee emp = new Employee("E001", "Eric Simmons");
          requestTo(new URI("http://localhost:8080/employee/E001")))
        Employee employee = empService.getEmployee(id);
        Assertions.assertEquals(emp, employee);                                                        

In the previous snippet, we used static methods from in MockRestRequestMatchers and MockRestResponseCreators to define the expectation and response for the REST call in a clear and readable way:

import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;      
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;

We should keep in mind that the RestTemplate in the test class should be the same instance used in the EmployeeService class. To ensure this, we defined a RestTemplate bean in the spring config and auto-wired the instance in both test and implementation:

public RestTemplate restTemplate() {
    return new RestTemplate();

Using a MockRestServiceServer is very useful when we write our integration tests and only need to mock external HTTP calls.

4. Conclusion

In this brief article, we discussed a few effective options for mocking the external REST API calls over HTTP while writing unit tests.

The source code for the above article is available over on GitHub.

Course – LS (cat=HTTP Client-Side)

Get started with Spring and Spring Boot, through the Learn Spring course:

res – HTTP Client (eBook) (cat=Http Client-Side)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.