Spring Boot lab (part 4): Testing the RestTemplate
What will be done here?
In the previous post I described how Spring Boot’s RestTemplate can be used to call Github’s API. In this post, we will implement a test for this RestTemplate.
Implementation
One way of writing a test for the funtionality that was implemented earlier could be a test for the controller. There is however one problem with this approach:If we only test the controller and simply rely on Github responding to the request, the test will be unstable because there is no guarantee that Github is always responding.
Instead, we will make use of Spring Boot’s capabilities to mock RestTemplate’s call to Github.
The test class looks as follows:
The class is annotated with RunWith(SpringRunner) and SpringBootTest which means that Spring Boot will start an application context with the main configuration. Next, the RestTemplate and the GithubRepositoryService are autowired. The member variable of type MockRestReserviceServer will be mocking Github’s response.
Ok, now the test case itself:
When the test is executed, a call to Github will be mocked and a json string will be returned. In that way the test case is not dependent on a working Github API.