Gmail Api Java客户端 - 使用mockito / powermock示例来模拟Gmail API调用

时间:2014-10-08 15:43:53

标签: mockito powermock google-api-java-client gmail-api

我们正在使用Gmail API Java客户端版本1.19.0。有没有人成功实现了一个可用于存根请求的工作模拟对象,例如:

gmailClient.users().history().list("me").setStartHistoryId(startHistoryId).setPageToken(pageToken).execute();

基本上,我们希望将上述调用存根并创建特定响应,以测试不同的业务场景。

3 个答案:

答案 0 :(得分: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);

}

答案 1 :(得分:0)

你可以嘲笑这些课程,因为他们不是最终的,等等。这里的限制是什么? (还没看过谷歌java客户端库的源代码,但不应该是特定于Gmail的 - 如果你发现有人在为另一个谷歌java客户端API做这个,你应该能够重复使用它。)

答案 2 :(得分:0)

对于这种情况,还有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;
      }
    };
  }
};