LittleQ
LittleQ

Reputation: 1925

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:

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

Thanks in advance!

Upvotes: 3

Views: 4025

Answers (1)

Morfic
Morfic

Reputation: 15508

Check the powermock documentation, depending on what you use, either mockito or easy mock. 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));
    }

}

Upvotes: 3

Related Questions