Solvedflutterfire Running Test throws MissingPluginException(No implementation found for method Firebase#initializeCore on channel plugins.flutter.io/firebase_core

Failing to write simple unit test using firebase emulators
Yesterday I upgrade to latest and greatest firebase/firestore plugins and decided to try out the firebase emulators to add some testing of my data access objects.

I fail to get the test up and running agains the emulators due to the error below

I saw some other issues that has been closed regarding the same error but with no solution that suited me.

I guess this is a simple mistake form my side in the code when connecting to the emulators.

MissingPluginException(No implementation found for method Firebase#initializeCore on channel plugins.flutter.io/firebase_core)

My test code

/// TODO: Get firebase emulators to work an use them for unit testing dao's
void main() {

  TournamentDao dao;

  setUpAll(() async {
    WidgetsFlutterBinding.ensureInitialized();

    await Firebase.initializeApp();
    FirebaseFirestore.instance.settings = Settings(host: 'localhost:8080', sslEnabled: false, persistenceEnabled: false);

    GetIt.I.registerSingleton<TournamentDao>(TournamentDaoImpl());
  });

  setUp(() {
    dao = GetIt.I<TournamentDao>();
  });

  test("TournamentDao.crud", () async {
   
    Tournament t = Tournament();
    t.name = 'Tezt';
    dao.create(t);

    var list = await dao.list(10);
    expect(list.length, 1);
  });

Firebase versions

  cloud_firestore: ^0.14.0
  firebase_auth: 0.18.0
  firebase_core: ^0.5.0
  firebase: ^7.3.0

Firebase emulators startup

firebase emulators:start
i  emulators: Starting emulators: functions, firestore, database, hosting
  functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: pubsub
  Your requested "node" version "10" doesn't match your global version "12"
i  firestore: Firestore Emulator logging to firestore-debug.log
i  database: Database Emulator logging to database-debug.log
i  hosting: Serving hosting files from: public
  hosting: Local server: http://localhost:5000
i  ui: Emulator UI logging to ui-debug.log
i  functions: Watching "/Users/gunnar/git/dart/chess-champion/functions" for Cloud Functions...

┌───────────────────────────────────────────────────────────────────────┐
   All emulators ready! View status and logs at http://localhost:4000 
└───────────────────────────────────────────────────────────────────────┘

┌───────────┬────────────────┬─────────────────────────────────┐
 Emulator   Host:Port       View in Emulator UI             
├───────────┼────────────────┼─────────────────────────────────┤
 Functions  localhost:5001  http://localhost:4000/functions 
├───────────┼────────────────┼─────────────────────────────────┤
 Firestore  localhost:8080  http://localhost:4000/firestore 
├───────────┼────────────────┼─────────────────────────────────┤
 Database   localhost:9000  http://localhost:4000/database  
├───────────┼────────────────┼─────────────────────────────────┤
 Hosting    localhost:5000  n/a                             
└───────────┴────────────────┴─────────────────────────────────┘
  Other reserved ports: 4400, 4500

Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.

Flutter doctor
Run flutter doctor and paste the output below:

Doctor summary (to see all details, run flutter doctor -v):
[] Flutter (Channel stable, 1.20.2, on Mac OS X 10.15.6 19G73, locale sv-SE)
 
[] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[] Xcode - develop for iOS and macOS (Xcode 11.6)
[] Android Studio (version 4.0)
[] IntelliJ IDEA Ultimate Edition (version 2020.2)
[] Connected device (1 available)

 No issues found!
33 Answers

✔️Accepted Answer

So I faced a similar issue in testing. I was attempting to create Document References during testing and calling await Firebase.initializeApp(); inside my setUpAll()

In my case I solved this by pulling the following file into my test directory which hooks into mock call handlers to be used throughout the test: https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore/test/mock.dart

For reference to contents of file:

// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

typedef Callback(MethodCall call);

setupCloudFirestoreMocks([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': {},
        }
      ];
    }

    if (call.method == 'Firebase#initializeApp') {
      return {
        'name': call.arguments['appName'],
        'options': call.arguments['options'],
        'pluginConstants': {},
      };
    }

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

    return null;
  });
}

Then in each test I would do the following:

void main() {
  setupCloudFirestoreMocks();

  setUpAll(() async {
    TestWidgetsFlutterBinding.ensureInitialized();

    await Firebase.initializeApp();
  });

// ALL MY TESTS WOULD BE HERE

}

Other Answers:

There are sometimes need to create an integration test (that does not involve bringing up a simulator) that tests the queries. For web apps, for example, I can bring up the firebase emulator and run integration tests for the queries against it. To reiterate, I don't want to test that the library works, I want to test that:

  1. My queries work
  2. I am using the library correctly (this is useful when I'm not familiar with a library).

I am also facing this issue. Everything runs fine except in testing.

I have the same issue. It works fine when I initialize the app in my actual app, but the same MissingPluginException gets thrown when I attempt the same thing in one of my simple tests.

So... Has anyone managed to run unit tests with FlutterFire ever? I'm getting the same issue and I don't even know if it is meant to work during unit testing or if I should give up the idea of testing...

More Issues: