这里是代码:
我该如何在单元测试中模拟
感谢您的提前帮助!
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()
,然后只需模拟整个类并覆盖创建实例的方法。 - Tuchkatanew
来初始化依赖项而不是应用Dependency Injection
会使模拟变得困难,因此您应该首先为CredentialsProvider
应用Dependency Injection
,然后再决定[测试第三方API vs.模拟第三方API]。 - Ahmed Nabil