简体   繁体   中英

JUnit test cases for FirebaseRemoteConfig in android using Mockito

How to write JUnit test cases for FirebaseRemoteConfig in android using Mockito.

I have tried this so far:

class MyUtilClassTest {
   @Test
   fun testKeyValue() {
      val context = mock(Context::class.java)
      FirebaseApp.initializeApp(Context)
      val keyValue = MyUtilClass.getKeyValue("keyName")
      assertTrue(keyValue)
   }
}

object MyUtilClass {
   fun getKeyValue(key: String) {
       FirebaseRemoteConfig.getInstance().getString(documentName)
       ...
   }
}

But getting this exception:

java.lang.NullPointerException
    at com.google.android.gms.common.internal.StringResourceValueReader.<init>(com.google.android.gms:play-services-basement@@17.3.0:5)
    at com.google.firebase.FirebaseOptions.fromResource(FirebaseOptions.java:156)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:242)

I would strongly recommend using Mockito to mock the MyUtilClass methods that rely on Firebase Remote Config rather than using it directly in your unit tests.

For example, something like this could work (apologies if the Mockito usage is not 100% accurate, it's been a while):

@Test
public void myTest {
  MyUtilClass mockUtilClass = Mockito.mock(MyUtilClass.class);
  Mockito.when(mockUtilClass.getKeyValue(eq("keyName")).thenReturn("expectedValue"));

  // Run test with mocked util class.
  testCodePath()

}

Note that while it makes sense to test Remote Config in a QA environment when deployed to tester devices, it's almost never a good idea to test Remote Config itself in a unit test. Rather than doing that, you can hardcode or mock the values you expect to be returned from Remote Config, and test your function or component based on those value sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM