[英]Flutter - Mockito Firestore...get() - The method 'document' was called on null
for learning purposes I am trying to mock a Firestore controller class with Mockito.出于学习目的,我试图用 Mockito 模拟 Firestore 控制器类。
firestore_controller.dart firestore_controller.dart
import 'package:cloud_firestore/cloud_firestore.dart';
class FirestoreController implements FirestoreControllerInterface {
final Firestore firestoreApi;
FirestoreController({this.firestoreApi});
@override
Future<DocumentSnapshot> read() async {
final DocumentSnapshot document = await this.firestoreApi.collection('user').document('user_fooBar').get();
return document;
}
}
firestore_controller_test.dart firestore_controller_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:mockito/mockito.dart';
import 'package:fooApp/Core/repositories/firebase/firestore_controller.dart';
class MockFirestoreBackend extends Mock implements Firestore {}
class MockDocumentSnapshot extends Mock implements DocumentSnapshot {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group("Firebase Controller", () {
final Firestore firestoreMock = MockFirestoreBackend();
final MockDocumentSnapshot mockDocumentSnapshot = MockDocumentSnapshot();
FirestoreController sut;
test("try to read a document", () async {
// Arrange
final Map<String, dynamic> _fakeResponse = {
'foo': 123,
'bar': 'foobar was here',
};
sut = FirestoreController(firestoreApi: firestoreMock); // INJECT MOCK
// Arrange: Mock
when(firestoreMock.collection('user').document('user_fooBar').get()).thenAnswer((_) => Future<MockDocumentSnapshot>.value(mockDocumentSnapshot));
when(mockDocumentSnapshot.data).thenReturn(_fakeResponse);
// Act
final fakeDocument = await sut.read();
});
});
}
🚨 Console Output 🚨 🚨控制台输出🚨
NoSuchMethodError: The method 'document' was called on null.
Receiver: null
Tried calling: document("user_fooBar")
sorry if the mistake is obvious, this is the first time I've used Mockito Where's my error?抱歉,如果错误很明显,这是我第一次使用 Mockito 我的错误在哪里? What do I miss?我想念什么? Thanks a lot!非常感谢!
try this:尝试这个:
https://pub.dev/packages/cloud_firestore_mocks https://pub.dev/packages/cloud_firestore_mocks
A test I've done using it:我使用它完成的测试:
class MockFirestore extends Mock implements Firestore {}
class MockDocument extends Mock implements DocumentSnapshot {}
void main() {
final _tAppointmentModel = AppointmentModel(
appointmentID: kAppointmentID,
date: DateTime.parse("2020-12-05 20:18:04Z"),
description: "test description",
doctorID: kDoctorID,
hospitalID: kHospitalID,
infantID: kInfantID,
);
group('AppointmentModel tests: ', () {
final tAppointmentID = kAppointmentID;
final tInfantID = kInfantID;
final tDoctorID = kDoctorID;
final tHospitalID = kHospitalID;
test('should be a subclass of Appointment', () async {
expect(_tAppointmentModel, isA<Appointment>());
});
test('store and retrieve document from Firestore', () async {
final instance = MockFirestoreInstance();
await instance.collection('appointments').add({
'appointmentID': tAppointmentID,
'date': DateTime.parse("2020-12-05 20:18:04Z"),
'description': "test description",
'doctorID': tDoctorID,
'hospitalID': tHospitalID,
'infantID': tInfantID,
});
final snapshot = await instance.collection('appointments').getDocuments();
final String expected = _tAppointmentModel.props[0];
final String result = snapshot.documents[0].data['appointmentID'];
expect(expected, result);
});
});
}
So I think I've found why this is - it appears to be a bug(ette) in Mockito, in that it doesn't handle the "dot walk" from collection(any) to document() or getDocuments().所以我想我已经找到了原因 - 它似乎是 Mockito 中的一个错误(ette),因为它不处理从集合(任何)到文档()或 getDocuments()的“点走”。 I fixed it like this:我是这样修复的:
declare five classes:声明五个类:
class MockFirebaseClient extends Mock implements Firestore {} //for your mock injection
class MockCollectionReference extends Mock implements CollectionReference {} //for when declaration
class MockQuerySnapshot extends Mock implements QuerySnapshot {} //for the thenAnswer return on collection of docs
class MockDocumentReference extends Mock implements DocumentReference {} //for single doc query
class MockDocumentSnapshot extends Mock implements DocumentSnapshot {} // for the thenAnswer return on single doc query
Do your setup etc - then the when clauses are just:做你的设置等 - 那么 when 子句只是:
when(mockCollectionReference.getDocuments())
.thenAnswer((_) => Future.value(mockQuerySnapshot)); //for collection of docs query
when(mockDocumentReference.get())
.thenAnswer((_) => Future.value(mockDocumentSnapshot)); //for single doc query
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.