在mockito中创建OkHttpClient时如何解决java.lang.AssertionError?

Tyl*_*aff 15 junit android mockito okhttp retrofit2

我正在努力让一些罐头网络响应.我对实际请求有json响应,并且我有Retrofit接口来序列化响应.试图设置它我感到非常沮丧.我该怎么办?看来我的选择是,1)使用MockWebServer()2)使用RequestInterceptor().

在尝试使用1或2时,我不能在我的生活中实例化OkHttpClient()而不会失败,基本上这会把我试图立即死亡的每一件事.我得到一个java.lang.AssertionError,因为当OkHttpClient无法找到TLS算法时会抛出它.

 if (builder.sslSocketFactory != null || !isTLS) {
      this.sslSocketFactory = builder.sslSocketFactory;
    } else {
      try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null);
        this.sslSocketFactory = sslContext.getSocketFactory();
      } catch (GeneralSecurityException e) {
        **throw new AssertionError(); // The system has no TLS. Just give up.**
      }
    }
Run Code Online (Sandbox Code Playgroud)

我试图使用unMock在android.jar中保留"javax.net.ssl"类,但这并没有解决错误.

unMock {
    // URI to download the android-all.jar from. e.g. https://oss.sonatype.org/content/groups/public/org/robolectric/android-all/
    downloadFrom 'https://oss.sonatype.org/content/groups/public/org/robolectric/android-all/4.3_r2-robolectric-0/android-all-4.3_r2-robolectric-0.jar'

    keep "android.util.Log"
    keep "javax.net.ssl"
}
Run Code Online (Sandbox Code Playgroud)

所以基本上,我已经遇到过如何通过改造2模拟网络请求的各种示例,但我无法克服这个障碍,而且我感觉很失败.我还没有看到其他人遇到过这个问题,而且我很困惑于每个人如何在所有测试中轻松实例化新的OkHttpClients.

以下是我正在使用的相关依赖项.

    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-all:1.10.19'
    testCompile 'org.powermock:powermock-mockito-release-full:1.6.4'
    testCompile 'org.powermock:powermock-module-junit4:1.6.4'
    testCompile 'org.easymock:easymock:3.4'
    testCompile 'org.powermock:powermock-api-easymock:1.6.4'
    testCompile 'com.squareup.okhttp3:mockwebserver:3.2.0'

    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
    compile 'com.google.code.gson:gson:2.4'
Run Code Online (Sandbox Code Playgroud)

Tyl*_*aff 65

您需要在课程顶部添加此注释.当然.

@PowerMockIgnore("javax.net.ssl.*")
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!它也适合我.你能解释一下为什么吗?这是okhttp或..的错误吗? (3认同)
  • FRR,这是一个 PowerMock 问题,后来被报告为他们这边的一个错误:https://github.com/powermock/powermock/issues/810。此处显示的解决方案和该问题中给出的解决方案一样有效(忽略特定的 HTTP 客户端库而不是 SSL 库):`@PowerMockIgnore("okhttp3.*")` (3认同)