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

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

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

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

但我在 "when" 调用期间收到错误消息,指出 GoogleCredential 对象内的 "lock" 实例为空。有什么方法可以让 Mockito 成功地存根方法调用吗?

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

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

这些更改允许该方法 mocked/stubbed 用于测试。

仅作记录,七年后您可以查看专为此目的而制作的 MockGoogleCredential。