2016-07-27 100 views
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); 
} 

提前感謝!

+1

你可以做的是創造一種新的方法,例如'createCredentialProviderInstance()',然後就嘲笑全班並重寫方法創建實例 – Tuchkata

+0

[如何測試具有私有方法,字段或內部類的類的可能的重複?](http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has -private-methods-fields-or-inner-classes) – Raedwald

+0

Tuchkata是正確的:你顯示的代碼真的很難測試。您應該將這些功能放入專門的工廠/供應商。當然,你仍然有PowerMock需要的第三方靜態呼叫......但不要陷入同一陷阱;相反,請確保至少您自己的**代碼是可測試的(請參閱https://www.youtube.com/playlist?list=PLD0011D00849E1B79以獲得一些啓發) – GhostCat

回答

2

檢查powermock文檔,具體取決於您使用的是mockito還是easy mock。下面根據的Mockito樣品,你的類的略微修改後的版本

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

} 
相關問題