Reputation: 421
Here's my controller:
@RequestMapping(
value = "/{owner}/{repositoryName}",
method = RequestMethod.GET,
produces = "application/json"
)
public RepoInfo repoInfo(@PathVariable String owner, @PathVariable String repositoryName) {
return restTemplate.getForObject(githubApiUrl + owner + "/" + repositoryName, RepoInfo.class);
}
And here are tests methods:
@Before
public void mockGithubApiResponse() {
Mockito.when(restTemplate.getForObject(githubApiUrl + dummyOwner + "/" + dummyRepoName, RepoInfo.class)).thenReturn(dummyRepoInfoObject);
}
@Test
public void shouldReturnRepoInfoObject() throws Exception {
Gson gson = new Gson();
String jsonRepo = gson.toJson(dummyRepoInfoObject);
this.mockMvc.perform(get("http://localhost:" + this.port + "/" + repoControllerMappingPrefix + dummyOwner + "/" + dummyRepoName)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(jsonRepo));
}
But it doesn't seem to mock anything. The controller is still responding based on external service.
Upvotes: 0
Views: 1870
Reputation: 816
I guess your RestTemplate declaration is like below
@Mock
RestTemplate restTemplate;
The cause is @Mock creates a mock instance in this class. Doesn't create in your actual controller class.
In this case, you can use MockRestServiceServer class for mocking RestTemplate class.
The following is the declaration of MockResrServiceServer
@Autowired
MockRestServiceServer mockServer;
The following is initialise of mockServer
mockServer = MockRestServiceServer.createServer(restTemplate);
}
And, this is setting up expectations and mock response.
mockServer.expect(requestTo("http://exleft-URL.com"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("resultSuccess"));
The above is just a sample you have to arrange them for your test code.
Upvotes: 2