Search code examples
mockitopowermockgoogle-api-java-clientgmail-api

Gmail Api Java Client - Use mockito/powermock example to mock Gmail API calls


We are using the Gmail API Java Client version 1.19.0. Is there anyone that has implemented successfully a working mock object that could be used for stubing requests such as:

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

Essentially, we would like to stub the above call and create a specific response, to test different business scenarios.


Solution

  • Please check below a working example of the above question. No need to use powermock. Mockito is only needed.

        @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);
    
    }