简体   繁体   English

如何在私有静态方法中模拟第三方类?

[英]How to mock a third-party class in private static method?

Here's the code: 这是代码:

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;
    }

}

How can I mock a CredentialsProvider when unit test: 单元测试时,如何模拟CredentialsProvider

@Test
public void testCreateAPIClient() {
    // mock a CredentialsProvider
    client = new APIClient();
    Assert.assertNotNull(client);
}

Thanks in advance! 提前致谢!

Check the powermock documentation, depending on what you use, either mockito or easy mock . 检查powermock文件,这取决于你用什么,无论是的Mockito容易模仿 Below a sample based on mockito and a slightly modified version of your classes 在下面的示例中,该示例基于模仿和您的类的稍加修改的版本

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.*;

// use appropriate test runner
@RunWith(PowerMockRunner.class)
// prepare the class calling the constructor for black magic
@PrepareForTest(APIClient.class)
public class APIClientTest {

    @Test
    public void testCreateAPIClient() throws Exception {
        // expectations
        String expectedAccessKey = "accessKeyId";
        String expectedSecretKey = "secretKey";
        Credentials credentials = new Credentials(expectedAccessKey, expectedSecretKey);

        // create a mock for your provider
        CredentialsProvider mockProvider = mock(CredentialsProvider.class);

        // make it return the expected credentials
        when(mockProvider.getCredentials()).thenReturn(credentials);

        // mock its constructor to return above mock when it's invoked
        whenNew(CredentialsProvider.class).withAnyArguments().thenReturn(mockProvider);

        // call class under test
        Identity actualIdentity = APIClient.createIdentity();

        // verify data & interactions
        assertThat(actualIdentity.getAttribute(Identity.ACCESS_KEY), is(expectedAccessKey));
        assertThat(actualIdentity.getAttribute(Identity.SECRET_KEY), is(expectedSecretKey));
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM