我如何用mockito模拟最终方法

时间:2014-10-17 00:21:22

标签: java junit mockito powermock

我试图用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();

}

1 个答案:

答案 0 :(得分: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));

希望它有所帮助。