我如何用mockito模拟最终方法



我试图用Mockito模拟一些对象,但我的代码不起作用。我的代码包含最后一个方法sslContext.init(..,..,..),我不知道如何修复它。

这是我想模仿的代码:

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

我认为您需要模拟特定的final方法。你能试着在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));

希望能有所帮助。

相关内容

  • 没有找到相关文章

最新更新