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();
}
是您對Mockito還是PowerMockito的問題? – 2014-10-17 02:37:33
我不回答這個問題,但我的(谷歌帶我到這裏...) 我使用mockserver。我需要模擬一個SSLContext。 mockserver已經提供了一個SSLFactory,它允許創建一個模擬的SSLContext。 – mcoolive 2016-09-29 09:16:21