Testing
#
OverviewThere 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.
#
Unit tests using fakesThe 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:
- https://pub.dev/packages/fake_cloud_firestore
- https://pub.dev/packages/firebase_storage_mocks
- https://pub.dev/packages/firebase_auth_mocks
- https://pub.dev/packages/google_sign_in_mocks
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.
#
Testing a Firestore appLet'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:
- MyHomePage
- MessageList
- ListTile
- ListTile
- ...
- FloatingActionButton
- MessageList
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:
MessageList
does render messages.- Tapping the
ActionButton
adds a "Hello world!" message to the database, and is also rendered.
In the tests, we pass a FakeFirebaseFirestore
to MyHomePage
. Since the fake instance is initially empty, we add some data so that MessageList
has something to display.
To run the tests, run flutter test
:
#
Integration tests using the Firestore Emulator- 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):