忽略 Roboelectric 单元测试中与 firebase 相关的异常

Ignore firebase related exceptions in Roboelectric unit test

当我尝试在应用程序中初始化 Firebase 时,我的 Roboelectric 单元测试给出了这个异常 class。

java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process null. Make sure to call FirebaseApp.initializeApp(Context) first.

有什么方法可以忽略此异常并通过测试?

组织您的代码,使其不依赖于 Firebase 连接并传入模拟?让单元测试依赖于远程服务通常不是一个好主意,这更像是集成测试或验收测试的领域。

或者,如果这太难了,请在@Before 中进行初始化?

如果您的测试中不需要 firebase,您可以将测试 class 注释为

@RunWith(RobolectricTestRunner.class)
@Config(application = Application.class)

使用与您的应用程序自定义应用程序不同的应用程序。

作为一个选项,您可以使用 mockito 中的 mockStatic:

mockStatic(FirebaseFirestore::class.java)
    .use { firebaseFirestore ->
        firebaseFirestore.`when`<Any> { FirebaseFirestore.getInstance() }.thenReturn(mock(FirebaseFirestore::class.java))
}