There are several ways to test apps that use Firebase:
- use fakes for unit and widget tests.
- use the actual Firebase service for integration tests. Alternatively, you can use the Firestore emulator.
As explained at https://flutter.dev/docs/testing, unit and widget tests are easier to maintain and run quickly. On the other hand, integration tests, while more thorough, run slower and require more configuration.
The Firebase libraries need to run on an actual device or emulator. So if you want to run unit tests, you'll have to use Fakes instead. A Fake is a library that implements the API of a given Firebase library and simulates its behavior. A few Fakes are available:
Note: despite the name, these libraries are Fakes, not Mocks.
When initializing your app, instead of passing the actual instance of a Firebase library (e.g.
FirebaseFirestore.instance if using Firestore), you pass an instance of a fake (e.g.
FakeFirebaseFirestore()). Then the rest of your application will run as if it were talking to Firebase.
Let's take a look at an old version of the Firestore sample app:
main() instantiates a
MyHomePage and passes an instance of Firestore to it. The UI is organized like so:
MessageList displays the messages stored in
firestore.collection("messages"), and each tap to the
ActionButton adds one "Hello world!" message to that same collection.
There are two things we can test:
MessageListdoes render messages.
- Tapping the
ActionButtonadds a "Hello world!" message to the database, and is also rendered.
In the tests, we pass a
MyHomePage. Since the fake instance is initially empty, we add some data so that
MessageList has something to display.
To run the tests, run
- Set up the Firestore Emulator according to the docs.
- Run the emulator:
firebase emulators:start --only firestore
- Set up your integration test to connect to your the emulator (sample code):