Deven Phillips
Deven Phillips

Reputation: 1139

How can I mock GoogleCredential in order to test my business logic

I am writing a unit test for one of my application and part of that requires mocking out the GoogleCredential object of the google-api-java-client. We use service accounts to authenticate between services in our SOA. I would like to do something like:

GoogleCredential cred = mock(GoogleCredential.class);
when(cred.refreshToken()).thenReturn(true);

But I get an error during the "when" call indicating that the "lock" instance inside of the GoogleCredential object is null. Is there some way to get Mockito to successfully stub the method call?

Upvotes: 2

Views: 6159

Answers (2)

cptsudoku
cptsudoku

Reputation: 51

Just for the record, seven years later you can check out MockGoogleCredential, made just for that purpose.

Upvotes: 0

Deven Phillips
Deven Phillips

Reputation: 1139

OK, so I had not realized that the method in question was "final", so I had to use PowerMockito to stub the final method. So, since I am using TestNG, I modified the class signature to "extends PowerMockTestCase" and added the class annotation "@PrepareForTest(GoogleCredential.class)"... Finally, in the test method:

PowerMockito.stub(credentials.getClass().getMethod("refreshToken")).toReturn(true);

Those changes allowed the method to be mocked/stubbed for testing.

Upvotes: 1

Related Questions