You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter测试中配置Firebase Remote Config Mock报空类型错误如何解决

错误原因
  • 当前Mock逻辑仅覆盖了Firebase核心初始化的两个方法Firebase#initializeCore和Firebase#initializeApp,未处理Firebase Remote Config专属的平台通道调用
  • Remote Config实例初始化时,会主动从平台侧拉取初始配置值(包括默认拉取超时时间、最小拉取间隔、配置参数等固定int类型字段),现有Mock逻辑中pluginConstants为空,且未响应Remote Config相关方法调用,返回的null无法匹配要求的int类型,触发类型错误。
修复方案
  1. 调整Mock函数,补全核心初始化时的Remote Config默认常量,同时添加Remote Config专属方法的响应逻辑,修正后的代码如下:
typedef Callback = dynamic Function(MethodCall call);

setupFirebaseRemoteConfigMocks([Callback? customHandlers]) {
  TestWidgetsFlutterBinding.ensureInitialized();

  MethodChannelFirebase.channel.setMockMethodCallHandler((call) async {
    if (call.method == 'Firebase#initializeCore') {
      return [
        {
          'name': defaultFirebaseAppName,
          'options': {
            'apiKey': '123',
            'appId': '123',
            'messagingSenderId': '123',
            'projectId': '123',
          },
          'pluginConstants': {
            'plugins.flutter.io/firebase_remote_config': {
              'minimumFetchInterval': 3600,
              'fetchTimeout': 10,
              'lastFetchTime': 0,
              'lastFetchStatus': 'success',
              'parameters': <String, dynamic>{}
            }
          },
        }
      ];
    }

    if (call.method == 'Firebase#initializeApp') {
      return {
        'name': call.arguments['appName'],
        'options': call.arguments['options'],
        'pluginConstants': {
          'plugins.flutter.io/firebase_remote_config': {
            'minimumFetchInterval': 3600,
            'fetchTimeout': 10,
            'lastFetchTime': 0,
            'lastFetchStatus': 'success',
            'parameters': <String, dynamic>{}
          }
        },
      };
    }

    // 响应Remote Config专属方法调用
    if (call.method.startsWith('FirebaseRemoteConfig#')) {
      switch(call.method) {
        case 'FirebaseRemoteConfig#setConfigSettings':
          return null;
        case 'FirebaseRemoteConfig#fetchAndActivate':
          return true; // 模拟拉取激活成功
        case 'FirebaseRemoteConfig#getAll':
          return <String, dynamic>{}; // 可替换为测试需要的配置键值对
        // 若测试中用到其他Remote Config方法,可在此处补充对应返回逻辑
      }
    }

    if (customHandlers != null) {
      return customHandlers(call);
    }

    return null;
  });
}
  1. 如需自定义测试用的配置参数,直接修改代码中parameters字段的键值对即可,例如测试某开关开启的场景可以写为'parameters': {'enable_new_feature': true}。
  2. 原有setUpAll中的初始化逻辑无需修改,直接使用更新后的Mock函数即可正常运行测试。

内容的提问来源于stack exchange,提问作者Chatura Dilan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:36:01