【问题标题】:Gmail Api Java Client - Use mockito/powermock example to mock Gmail API callsGmail Api Java 客户端 - 使用 mockito/powermock 示例模拟 Gmail API 调用
【发布时间】:2014-10-08 15:43:52
【问题描述】:
我们使用的是 Gmail API Java 客户端版本 1.19.0。有没有人成功实现了一个可用于存根请求的工作模拟对象,例如:
gmailClient.users().history().list("me").setStartHistoryId(startHistoryId).setPageToken(pageToken).execute();
本质上,我们希望对上述调用进行存根并创建一个特定的响应,以测试不同的业务场景。
【问题讨论】:
标签:
mockito
powermock
google-api-java-client
gmail-api
【解决方案1】:
请在下方查看上述问题的工作示例。无需使用 powermock。只需要 Mockito。
@Before
public void init() throws Exception{
ListHistoryResponse historyResponse = new ListHistoryResponse();
historyResponse.setHistoryId(BigInteger.valueOf(1234L));
List<History> historyList = new ArrayList<>();
History historyEntry = new History();
Message message = new Message();
message.setId("123456");
message.setThreadId("123456");
List<Message> messages = new ArrayList<>();
messages.add(message);
historyEntry.setMessages(messages);
historyList.add(historyEntry);
mock = mock(Gmail.class);
Gmail.Users users = mock(Gmail.Users.class);
Gmail.Users.History history = mock(Gmail.Users.History.class);
Gmail.Users.History.List list = mock(Gmail.Users.History.List.class);
when(mock.users()).thenReturn(users);
when(users.history()).thenReturn(history);
when(history.list("me")).thenReturn(list);
when(list.setStartHistoryId(BigInteger.valueOf(123L))).thenReturn(list);
when(list.setPageToken(null)).thenReturn(list);
when(list.execute()).thenReturn(historyResponse);
}
【解决方案2】:
你可以模拟这些类,只要它们不是最终的,等等。这里有什么限制? (没有查看 Google java 客户端库的源代码,但不应该是特定于 gmail 的——如果你发现有人为另一个 Google java 客户端 API 做这件事,你应该能够重用它)。
【解决方案3】:
对于这种情况,还有MockHttpTransport 辅助类。请查阅文档chapter HTTP Unit Testing
HttpTransport transport = new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.addHeader("custom_header", "value");
response.setStatusCode(404);
response.setContentType(Json.MEDIA_TYPE);
response.setContent("{\"error\":\"not found\"}");
return response;
}
};
}
};