Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock FirebaseRemoteConfig getBoolean()

I have a unit test that requires me to return either a true or false for a firebase config entry. But even if I set the mock to true it always returns false when the unit test is run.

Here is my mock:

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

And here is the code with the true or false condition

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

useHttp is always false

Test dependencies:

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

Any ideas would be appreciated!

like image 623
Francois Avatar asked Feb 24 '26 16:02

Francois


1 Answers

Your first statement is equivalent to this:

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

It does not work, because your productive code is not using that mock (it will not be returned by FirebaseRemoteConfig.getInstance()).

You need a way to inject the mock into the tested class, e.g.

  • pass it into the tested method
  • pass it into the constructor
  • call FirebaseRemoteConfig.getInstance() in a protected method, that is spied in the test
like image 165
Darkwyng Avatar answered Feb 27 '26 05:02

Darkwyng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!