2014-10-17 70 views
1

我想用Mockito來模擬一些對象,但是我的代碼不工作。我的代碼包含一個最終的方法sslContext.init(..,..,..),我不知道如何解決這個問題。我怎樣才能用mockito來模擬最後的方法

這是我的代碼,我想嘲笑:

public class MYClass { 
private SSLSocketFactory sslSocketFactory; 
public MyClass() throws IOException{ 
    String trustStoreFilePath = System.getProperty("javax.net.ssl.trustStore"); 
    try { 
      TrustManagerFactory trustManagerFactory = CertManagerFactory.loadTrustStore(trustStoreFilePath); 
      SSLContext sslContext = SSLContext.getInstance("TLS"); 
      sslContext.init(null, trustManagerFactory.getTrustManagers(), null); 
      this.sslSocketFactory = sslContext.getSocketFactory(); 
     } 
     catch (NoSuchAlgorithmException e) {} 
     catch (KeyManagementException e) {} 
    } 
} 

,我的代碼是:


@RunWith(PowerMockRunner.class) 
@PrepareForTest({CertManagerFactory.class, SSLContext.class}) 
public class MyClassTest{ 

@Before 
public void setUp() throws IOException, NoSuchAlgorithmException, KeyManagementException { 

    PowerMockito.mockStatic(CertManagerFactory.class, SSLContext.class);   
    SSLContext sslContextMock = mock(SSLContext.class); 
    SSLSocketFactory sSLSocketFactoryMock = mock(SSLSocketFactory.class); 
    TrustManagerFactory trustManagerFactoryMock = mock(TrustManagerFactory.class); PowerMockito.when(CertManagerFactory.loadTrustStore(anyString())).thenReturn(trustManagerFactoryMock); 
    PowerMockito.when(SSLContext.getInstance(anyString())).thenReturn(sslContextMock); 
    when(trustManagerFactoryMock.getTrustManagers()).thenReturn(any(TrustManager[].class)); 
    when(sslContextMock.getSocketFactory()).thenReturn(sSLSocketFactoryMock); 
    MyClass myClass= new MyClass(); 

} 

+0

是您對Mockito還是PowerMockito的問題? – 2014-10-17 02:37:33

+0

我不回答這個問題,但我的(谷歌帶我到這裏...) 我使用mockserver。我需要模擬一個SSLContext。 mockserver已經提供了一個SSLFactory,它允許創建一個模擬的SSLContext。 – mcoolive 2016-09-29 09:16:21

回答

2

我認爲你需要模擬特定的最終方法。你可以嘗試後SSLContext sslContextMock = mock(SSLContext.class);

PowerMockito.doNothing().when(sslContextMock).init(any(KeyManager[].class), any(TrustManager[].class), any(SecureRandom.class)); 

添加此行如果你想模擬KeyManagementException投擲,你可以做如下:

PowerMockito.doThrow(new KeyManagementException()).when(sslContextMock).init(any(KeyManager[].class), any(TrustManager[].class), any(SecureRandom.class)); 

希望它能幫助。

+0

非常感謝。順便說一下,如何驗證異常拋出的輸出錯誤消息。 – houchker 2014-10-19 22:32:21