在运行模块的检测测试时禁用 Firebase 初始化

问题描述 投票:0回答:3

我有一个多模块项目。我希望能够分别运行我为这些模块编写的仪器测试。当我运行测试并初始化活动时,我不断遇到以下错误。

默认FirebaseApp在此过程中未初始化。确保首先调用 FirebaseApp.initializeApp(Context)。

我尝试在测试代码中使用测试应用程序的上下文显式调用此函数,但无济于事。我知道 firebase 是通过配置文件设置的,但我没有明确调用它来设置它。在实际应用程序启动之前,它会通过内容提供商(阅读博客)自动初始化。

因为这将是一个静态调用,并且我们没有显式调用它,所以我也看不到模拟它的方法。有没有办法在我的模块中完全禁用 UITest 运行的 firebase?

android firebase gradle android-instrumentation
3个回答
2
投票

Firebase 使用内容提供程序在应用程序的 onCreate() 方法之前连接库。 该内容提供者已在库中注册

com.google.firebase.firebase-perf
(通过行
platform("com.google.firebase:firebase-bom:...
从您的 build.gradle 文件中导入)

要阻止 firebase 连接过程问题,您可以:

  1. 为 android-test 创建一个自定义应用程序类,在应用程序的
    onCreate()
    中调用一次 FirebaseApp.initializeApp() (如果您希望 Firebase 在 Android 测试中正确设置和可测试,则很好)
  2. 禁用 Firebase 的提供程序(如果您不需要 Fire,则完美,但如果您在测试代码中使用 Firebase 服务(例如 creashlytics 等),则可能会导致问题)

如何做?


创建自定义应用程序类:

  1. 在文件夹
    src/androidTest/
    中创建文件
    MyCustomTestApp.kt
    (或任何其他类名),内容为:
package <...> // use the default package that was set when you created the file

import android.app.Application
import com.google.firebase.FirebaseApp

class MyCustomTestApp: Application() {
    override fun onCreate() {
        super.onCreate()
        FirebaseApp.initializeApp(this)
    }
}
  1. 在文件
    src/androidTest/AndroidManifest.xml
    文件中(如果尚不存在则创建新文件)添加以下内容:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
        android:name="here setup the path to your custom application class, e.g. com.yourApp.package.name.MyCustomTestApp"
        tools:replace="android:name">

        <--! if you have test activities etc, you register them here ... -->

    </application>
</manifest>

完全禁用 firebase 的内容提供程序:

在文件

src/androidTest/AndroidManifest.xml
文件中(如果尚不存在则创建新文件)添加以下内容:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application>

        <!-- disable firebase provider to get rid of "Default FirebaseApp is not initialized in this process" exceptions -->
        <provider
            android:authorities="${applicationId}.firebaseperfprovider"
            android:name="com.google.firebase.perf.provider.FirebasePerfProvider"
            tools:node="remove" />

    </application>
</manifest>


0
投票

我遇到了同样的问题,幸运的是我找到了这个线程。我可以确认上面 Re'em 的答案是正确的,但有一个小问题,即 androidTest 的 AndroidManifest.xml 被忽略。您可以在这里找到此问题的解决方案。 androidTest目录中的AndroidManifest被忽略


-1
投票

如果您有一个可以监听的环境值,或者您的应用程序中有一个您可以知道在这些条件下存在或不存在的状态,您可以根据需要启动它。然而,这确实需要 ALL Firebase 调用进行运行状况检查,以防止它们在

apps.length == 0

时触发
if (firebase.apps.length > 0) {
    // run firebase request
}

if (firebase.apps.length == 0) return;
© www.soinside.com 2019 - 2024. All rights reserved.