I am trying to mock some objects with Mockito, but my code doesn't work. My code contains one final method sslContext.init(..,..,..)
, and I don't know how to fix that.
This is my code that I want to mock :
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) {}
}
}
and my code is :
@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();
}