Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock Firebase Crashlytics using Mockito in a Dart app?

I am using Firebase Crashlytics in a Flutter app and I want to write a unit test for the code snippet below:

if (queryResult.hasException) {
  String msg = queryResult.exception.toString();
  await FirebaseCrashlytics.instance.recordError(error, stackTrace, reason: message, fatal: true);
  throw Exception("Query execution failed due to: " + msg);
}

Is there a way to mock the Firebase instance and don't record the error in my unit tests?

The following exception is thrown if I don't mock it:

 No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
like image 814
Razvan Puiu Avatar asked Oct 27 '25 22:10

Razvan Puiu


1 Answers

I couldn't find any out-of-the-box solution, so I had to implement my own mock as follows:

import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:meta/meta.dart';

class Report {

  static FirebaseCrashlytics _firebaseCrashlytics = FirebaseCrashlytics.instance;

  @visibleForTesting
  static set firebaseCrashlytics(FirebaseCrashlytics value) {
    _firebaseCrashlytics = value;
  }
}

In the test, I do:

@GenerateMocks([FirebaseCrashlytics])
void main() {
  late MockFirebaseCrashlytics firebaseCrashlyticsMock;

  setUp(() {
    firebaseCrashlyticsMock = MockFirebaseCrashlytics();
    Report.firebaseCrashlytics = firebaseCrashlyticsMock;
  });

  test("", (){
    ...
    when(firebaseCrashlyticsMock.recordError(any, any, fatal: true)).thenAnswer((_) => Future.value("output"));
    ...
  });

Now I can send custom reports to Crashlytics and also have some unit tests.

like image 158
Razvan Puiu Avatar answered Oct 30 '25 07:10

Razvan Puiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!