0
下面的代碼:如何在私有靜態方法中模擬第三方類?
public final class APIClient {
private static Identity identity = createIdentity();
private static Identity createIdentity() {
CredentialsProvider provider = new CredentialsProvider(API_USER);
Credentials creds = provider.getCredentials();
identity = new Identity();
identity.setAttribute(Identity.ACCESS_KEY, creds.getAccessKeyId());
identity.setAttribute(Identity.SECRET_KEY, creds.getSecretKey());
return identity;
}
}
我如何可以模擬一個CredentialsProvider
時,單元測試:
@Test
public void testCreateAPIClient() {
// mock a CredentialsProvider
client = new APIClient();
Assert.assertNotNull(client);
}
提前感謝!
你可以做的是創造一種新的方法,例如'createCredentialProviderInstance()',然後就嘲笑全班並重寫方法創建實例 – Tuchkata
[如何測試具有私有方法,字段或內部類的類的可能的重複?](http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has -private-methods-fields-or-inner-classes) – Raedwald
Tuchkata是正確的:你顯示的代碼真的很難測試。您應該將這些功能放入專門的工廠/供應商。當然,你仍然有PowerMock需要的第三方靜態呼叫......但不要陷入同一陷阱;相反,請確保至少您自己的**代碼是可測試的(請參閱https://www.youtube.com/playlist?list=PLD0011D00849E1B79以獲得一些啓發) – GhostCat