org.mockito.exceptions.misusing.NotAMockException:参数应该是一个模拟,但是是:class java.lang.Class for Android SSLContext.getInstance() metho

org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class for Andriod SSLContext.getInstance() metho

我正在研究 Android 和 PowerMock 项目。在这个例子中,我试图模拟下面的方法,但是我得到了错误

org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class

    at com.ABCTest.testTrustAppCertificates(ABCTest.java:314)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitS

代码:

private void trustAppCertificates(boolean isTrustAll) {
    try {
        TrustManager[] trustAllCerts = // get the Trust Manager 
        SSLContext sc = SSLContext.getInstance("TLSv1.2"); // Line-4
        sc.init(null, trustAllCerts, new SecureRandom()); // Line-5
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier((arg0, arg1) -> isTrustAll);
    } catch (Exception e) {
        // LOG ERROR HERE
    }
}

测试用例:

@PowerMockIgnore({"org.apache.http.conn.ssl.*", "javax.net.ssl.*" , "javax.crypto.*"})
@Test
public void testTrustAppCertificates() throws Exception {
    ...
    ...
    ...
    PowerMockito.mockStatic(SSLContext.class);
    SSLContext sslContextMock = mock(SSLContext.class);
    PowerMockito.doNothing().when(sslContextMock).init(any(KeyManager[].class), any(TrustManager[].class), any(SecureRandom.class));

    PowerMockito.when(SSLContext.getInstance(anyString())).thenReturn(sslContextMock); // This line breaks and gives the error mentioned above
    when(sslContextMock.getSocketFactory()).thenReturn(sSLSocketFactoryMock);

    PowerMockito.verifyPrivate(mockClass).invoke("trustAppCertificates", true);
}

您可以使用以下代码解决问题。希望这会帮助你。请替换行下方

PowerMockito.when(SSLContext.getInstance(anyString())).thenReturn(sslContextMock);

when(SSLContext.getInstance(anyString())).thenAnswer((Answer<SSLContext>) invocation -> sslContextMock);