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

标签 android junit mockito okhttp retrofit2

我正在尝试制作一些 jar 装网络响应。我有实际请求的 json 响应,我有序列化响应的 Retrofit 接口(interface)。尝试设置它让我感到非常沮丧。我应该在这里做什么?看来我的选择是,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.**
      }
    }

我尝试使用 unMock 将“javax.net.ssl”类保留在 android.jar 中,但这并没有解决错误。

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"
}

所以基本上,我遇到过各种关于如何使用 retrofit 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'

最佳答案

您需要在类的顶部添加此注释。当然。

@PowerMockIgnore("javax.net.ssl.*")

关于android - 在 mockito 中创建 OkHttpClient 时如何解决 java.lang.AssertionError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36167571/

相关文章:

java - Mockito - 验证 stub

java - PowerMock 抛出 java.lang.ExceptionInInitializerError

java - Android ListView - 奇怪的回收行为

android - 如何为 Android 创建一个简单的 2D 游戏?

android - 如何使用位置管理器但没有位置监听器获取 Android 当前位置 "only on demand"?

java - Eclipse 未找到类定义 - Loadrunner lr.class

java - 如何模拟返回模拟对象的方法

android - 渲染到纹理和同步

java - 简单发送/接收多线程总是给出空异常

c# - 将一项测试应用于两个不同的类(class)