如何模拟GoogleCredential以测试我的业务逻辑

时间:2015-01-23 17:38:04

标签: java unit-testing mockito google-api-java-client

我正在为我的一个应用程序编写单元测试,其中一部分需要模拟google-api-java-client的GoogleCredential对象。我们使用服务帐户在SOA中的服务之间进行身份验证。我想做点什么:

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

但是在"""呼叫表示"锁定" GoogleCredential对象内的实例为null。有没有办法让Mockito成功存根方法调用?

1 个答案:

答案 0 :(得分:1)

好的,所以我没有意识到所讨论的方法是" final",所以我不得不使用PowerMockito来存根最终方法。因此,由于我使用的是TestNG,我将类签名修改为"扩展了PowerMockTestCase"并添加了类注释" @PrepareForTest(GoogleCredential.class)" ...最后,在测试方法中:

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

这些更改允许对方法进行模拟/存根以进行测试。