Skip to content

Mocking Firebase Analytics for unit tests(Flutter)

Dart, Flutter, Issues1 min read

Recently, I encountered an issue while upgrading Flutter and some outdated packages in one of my projects. Specifically, after upgrading the firebase_analytics package, I faced problems with some of my unit tests. In this article, I will share the steps I took to troubleshoot and resolve this issue.

Identifying the Problem

Upon upgrading the firebase_analytics package, I noticed that my previously functioning unit tests were now failing. It appeared that changes had been made to the package since my last update, leading to compatibility issues. Although I couldn't pinpoint the exact cause, I observed that any attempts to make calls that would send events resulted in an error message instructing me to initialize the library, even though initialization did not resolve the issue. The specific error message I encountered was as follows:

1[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

Resolving the Issue with Mocking

To solve the problem, I decided to create a mock for the AnalyticsUtil class using the mockito package, which I had used previously to mock navigation in a unit test (as discussed in my previous article here). But this time I didn't need to use any code generation.

In my project I had a simple AnalyticsUtil class, which I used in conjunction with riverpod. The class looked like this:

1import 'package:firebase_analytics/firebase_analytics.dart';
2import 'package:logger/logger.dart';
4class AnalyticsUtil {
5 final _logger = Logger();
7 void logEvent({
8 required String name,
9 Map<String, dynamic>? parameters,
10 }) {
11 _logger.d('Sending analytics event: $name');
12 if (parameters != null) {
13 FirebaseAnalytics.instance.logEvent(
14 name: name,
15 parameters: parameters,
16 );
17 } else {
18 FirebaseAnalytics.instance.logEvent(
19 name: name,
20 );
21 }
22 }

The specifics of integrating this class with riverpod are beyond the scope of this article, I'll focus on the solution to the firebase_analytics upgrade issue.

To create a mock for the AnalyticsUtil class, follow these steps:

  1. Install the mockito package.
  2. Define a new class, _AnalyticsMock, which extends Mock from mockito, and overrides the logEvent method as follows:
1import 'package:mockito/mockito.dart';
3class _AnalyticsMock extends Mock implements AnalyticsUtil {
4 @override
5 void logEvent({required String name, Map<String, dynamic>? parameters}) {}
  1. In your unit test, create an instance of _AnalyticsMock to use in place of the actual AnalyticsUtil class:
1final analytics = _AnalyticsMock();

By utilizing the mock class in your tests or injecting it into other classes, you can avoid encountering issues when calling logEvent within your view models or elsewhere. And off you go - you won't have any issues anymore if you are calling logEvent somewhere in your view models etc.