4

I'm new to unit testing in general. I'm trying to test simple method from my DataRepository.

Following this link but seems deprecated: https://utkarshkore.medium.com/writing-unit-tests-in-flutter-with-firebase-firestore-72f99be85737

class DataRepository {
  final CollectionReference collection =
      FirebaseFirestore.instance.collection('notes');

  //Retour de models a la place de snapshots
  Stream<QuerySnapshot> getStream() {
    return collection.snapshots();
  }

  Stream<QuerySnapshot> getStreamDetail(String id) {
    return collection.doc(id).collection('tasks').snapshots();
  }

  Stream<List<Note>> noteStream() {
    final CollectionReference collection =
        FirebaseFirestore.instance.collection('notes');

    try {
      return collection.snapshots().map((notes) {
        final List<Note> notesFromFirestore = <Note>[];
        for (var doc in notes.docs) {
          notesFromFirestore.add(Note.fromSnapshot(doc));
        }
        return notesFromFirestore;
      });
    } catch (e) {
      rethrow;
    }
  }

So far this is what my test file look like:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';

class MockFirestore extends Mock implements FirebaseFirestore {}
class MockCollectionReference extends Mock implements CollectionReference {}

void main() {
  MockFirestore instance = MockFirestore();
  MockCollectionReference mockCollectionReference = MockCollectionReference();

  test('should return data when the call to remote source is succesful.',
      () async {
    when(instance.collection('notes')).thenReturn(mockCollectionReference);
  });
}

First instance throw me this error

The argument type 'MockCollectionReference' can't be assigned to the parameter type 'CollectionReference<Map<String, dynamic>>'

I would really appreciate the help for testing the method.

new edit:

void main() {
  test('should return data when the call to remote source is succesful.',
      () async {
    final FakeFirebaseFirestore fakeFirebaseFirestore = FakeFirebaseFirestore();
    final DataRepository dataRepository = DataRepository();
    final CollectionReference mockCollectionReference =
        fakeFirebaseFirestore.collection(dataRepository.collection.path);

    final List<Note> mockNoteList = <Note>[];

    for (Note mockNote in mockNoteList) {
      await mockCollectionReference.add(mockNote.toJson());
    }

    final Stream<List<Note>> noteStreamFromRepository =
        dataRepository.noteStream();

    final List<Note> actualNoteList = await noteStreamFromRepository.first;
    final List<Note> expectedNoteList = mockNoteList;

    expect(actualNoteList, expectedNoteList);
  });
}
3
  • Did you try to use mocktail package for mocking dependencies? Mar 6, 2022 at 13:02
  • Please include more code specifically the DataRepository class and the Note class. I've also added an answer below with the information you have up there. Mar 6, 2022 at 15:00
  • 1
    Hi @WilliKim, please remember to react to answers for your questions. That way we know if the answers were helpful and other community members could also benefit from them. Try to accept answer that is the final solution for your issue, upvote answers that are helpful and comment on those which could be improved or require additional attention. Enjoy your stay! Mar 7, 2022 at 15:24

2 Answers 2

11

You can use the fake_cloud_firestore to mock the Firestore instance by using it's FakeCloudFirestore object that can be used in the place of an actual FirebaseFirestore object.

An Example:

 import 'package:cloud_firestore/cloud_firestore.dart';
 import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';

 test('noteStream returns Stream containing List of Note objects', () async {
      //Define parameters and objects

      final FakeFirebaseFirestore fakeFirebaseFirestore = FakeFirebaseFirestore();

      final DataRepository dataRepository =
          DataRepository(firestore: fakeFirebaseFirestore);

      final CollectionReference mockCollectionReference =
          fakeFirebaseFirestore.collection(dataRepository.collection.path);

      final List<Note> mockNoteList = [Note()];

      // Add data to mock Firestore collection
      for (Note mockNote in mockNoteList) {
        await mockCollectionReference.add(mockNote.toSnapshot());
      }

      // Get data from DataRepository's noteStream i.e the method being tested
      final Stream<List<Note>> noteStreamFromRepository =
          dataRepository.noteStream();

      final List<Note> actualNoteList = await noteStreamFromRepository.first;

      final List<Note> expectedNoteList = mockNoteList;

      // Assert that the actual data matches the expected data
      expect(actualNoteList, expectedNoteList);
    });

Explanation:

The test above makes the following assumptions about your code:

  • You pass the FirebaseFirestore object into the DataRepository object.
  • You have a toSnapshot method on your Note object which converts your Note object into a Map<String, dynamic> object.

The test works into the following way:

  1. It creates the necessary objects needed for the test i.e the FakeFirebaseFirestore object, the DataRepository object, the mock CollectionReference object and the mock data to be passed into the mock collection reference (mockNoteList).
  2. It adds the data into the mock collection reference.
  3. It gets the data using the DataRepository's noteStream method.
  4. It asserts that the actual data from the DataRepository is equal to the expected data i.e the data passed originally into the mock collection reference.

Resources:

For more understanding on unit testing Firestore in Flutter, check out the following resources:

Update

Add the FirebaseFirestore object as one of your constructor parameters and use that instead of FirebaseFirestore.instance.

Update your DataRepository to this below:

class DataRepository {
  DataRepository({required this.firestore});

  final FirebaseFirestore firestore;

   CollectionReference get collection =>
     firestore.collection('notes');

  //Retour de models a la place de snapshots
  Stream<QuerySnapshot> getStream() {
    return collection.snapshots();
  }

  Stream<QuerySnapshot> getStreamDetail(String id) {
    return collection.doc(id).collection('tasks').snapshots();
  }

  Stream<List<Note>> noteStream() {
    try {
      return collection.snapshots().map((notes) {
        final List<Note> notesFromFirestore = <Note>[];
        for (var doc in notes.docs) {
          notesFromFirestore.add(Note.fromSnapshot(doc));
        }
        return notesFromFirestore;
      });
    } catch (e) {
      rethrow;
    }
  }

Updated DataRepository Usage:

  • In tests:
 final FakeFirebaseFirestore fakeFirebaseFirestore = FakeFirebaseFirestore();
 final DataRepository dataRepository =
          DataRepository(firestore: fakeFirebaseFirestore);
  • In the app:
 final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
 final DataRepository dataRepository =
          DataRepository(firestore: firebaseFirestore);
10
  • Thank you so much for the answer my DataRepository just have a instance like this class DataRepository { final CollectionReference collection = FirebaseFirestore.instance.collection('notes'); and like you guessed I have a map snapshot
    – Willy Kim
    Mar 6, 2022 at 20:54
  • Can you tell me why you use FakeCloudFirestore ? What does it add more than mockito only ?
    – Willy Kim
    Mar 6, 2022 at 20:55
  • @WillyKim, I used FakeCloudFirestore instead of mockito because it already implements the methods/operations that FirebaseFirestore supports and you can easily mock the state of the database by adding data to it like you would do with the FirebaseFirestore object. Mar 6, 2022 at 22:24
  • 1
    You're getting that error most likely because you're still using the FirebaseFirestore object when you should be using FakeFirebaseFirestore. Please share the test code. Mar 8, 2022 at 11:30
  • 1
    @BillTurner the Firestore instance is passed to be able to use a mocked version of Firestore in tests. FirebaseFirestore.instance is the "real" Firestore object used in the app while FakeFirestore() is the mock version that allows you add data to it in tests. Feb 24 at 0:16
1

This should solve your problem: Specify a type for CollectionReference. This way:

class MockCollectionReference extends Mock implements CollectionReference<Map<String, dynamic>> {}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.