I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Introduction

Frequently, we find ourselves with applications which 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 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 could 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:

@Service
public class EmployeeService {
    
    @Autowired
    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;
    }
}

Let’s implement our test for the previous code:

@RunWith(MockitoJUnitRunner.class)
public class EmployeeServiceTest {

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private EmployeeService empService = new EmployeeService();

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

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

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

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

Finally, in the test method, we’ve 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. Finally, we can verify() on that server instance whether all expectations have been met or not.

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:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringTestConfig.class)
public class EmployeeServiceMockRestServiceServerUnitTest {

    @Autowired
    private EmployeeService empService;
    @Autowired
    private RestTemplate restTemplate;

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

    @Before
    public void init() {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }
    
    @Test                                                                                          
    public void givenMockingIsDoneByMockRestServiceServer_whenGetIsCalled_thenReturnsMockedObject()() {   
        Employee emp = new Employee("E001", "Eric Simmons");
        mockServer.expect(ExpectedCount.once(), 
          requestTo(new URI("http://localhost:8080/employee/E001")))
          .andExpect(method(HttpMethod.GET))
          .andRespond(withStatus(HttpStatus.OK)
          .contentType(MediaType.APPLICATION_JSON)
          .body(mapper.writeValueAsString(emp))
        );                                   
                       
        Employee employee = empService.getEmployee(id);
        mockServer.verify();
        Assert.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 that, we have defined a RestTemplate bean in the spring config and auto-wired the instance in both test and implementation:

@Bean
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 have 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.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

avatar
  Subscribe  
Notify of