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);
});
}
DataRepository
class and theNote
class. I've also added an answer below with the information you have up there.