【问题标题】:Mock FirebaseRemoteConfig getBoolean()模拟 FirebaseRemoteConfig getBoolean()
【发布时间】:2020-02-07 05:59:13
【问题描述】:

我有一个单元测试,要求我返回 truefalse 以获得 firebase 配置条目。但即使我将模拟设置为true,它在运行单元测试时也总是返回false

这是我的模拟:

doReturn(true).when(mock(FirebaseRemoteConfig.class)).getBoolean(any());

这是带有truefalse 条件的代码

FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
boolean useHttp = firebaseRemoteConfig.getBoolean(RemoteConfigKeys.PUSH_RECEIVED_USE_HTTP);

useHttp 始终是false

测试依赖:

    // Unit test dependencies
    testImplementation 'androidx.test:core:1.2.0'
    testImplementation "androidx.work:work-testing:2.2.0"
    testImplementation 'org.junit.jupiter:junit-jupiter:5.5.2'
    testImplementation 'org.robolectric:robolectric:4.3.1'
    testImplementation 'org.robolectric:shadows-playservices:4.3.1'
    testImplementation 'org.mockito:mockito-core:2.24.5'
    testImplementation 'com.google.truth:truth:1.0'
    testImplementation 'com.google.android.material:material:1.0.0'
    testImplementation "com.squareup.leakcanary:leakcanary-android:2.0-beta-5"
    kaptTest 'org.parceler:parceler:1.1.12'
    kaptTest "com.google.dagger:dagger-compiler:2.25.4"

任何想法都将不胜感激!

【问题讨论】:

  • 你有没有想过这个问题?如果是这样的话,我很想看看你是怎么做到的:)

标签: android firebase junit mockito firebase-remote-config


【解决方案1】:

你的第一个语句是这样的:

FirebaseRemoteConfig aTemporaryExistingJavaObject = mock(FirebaseRemoteConfig.class);
doReturn(true).when(aTemporaryExistingJavaObject).getBoolean(any());

它不起作用,因为您的生产代码没有使用该模拟(FirebaseRemoteConfig.getInstance() 不会返回它)。

您需要一种将模拟注入测试类的方法,例如

  • 将其传递到测试方法中
  • 将其传递给构造函数
  • 在受保护的方法中调用 FirebaseRemoteConfig.getInstance(),该方法在测试中被监视

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多