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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With