这是我的 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);
}
以下是测试方法:
@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));
}
但它似乎并没有 mock 任何东西。 Controller 仍在根据外部服务进行响应。
最佳答案
我猜你的 RestTemplate 声明如下
@Mock
RestTemplate restTemplate;
原因是 @Mock 在此类中创建了一个模拟实例。不在您的实际 Controller 类中创建。
在这种情况下,您可以使用 MockRestServiceServer 类来模拟 RestTemplate 类。
以下是MockResrServiceServer的声明
@Autowired
MockRestServiceServer mockServer;
以下是mockServer的初始化
mockServer = MockRestServiceServer.createServer(restTemplate);
}
而且,这是建立期望和模拟响应。
mockServer.expect(requestTo("http://exleft-URL.com"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("resultSuccess"));
以上只是一个示例,您必须为您的测试代码安排它们。
关于java - 模拟restTemplate的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41505444/