Reputation: 2787
Before anything else I want to clarify that I'm asking about Firebase Realtime Database
and not Firestore
.
Background:
I have an app that uses both Firestore and Firebase Realtime database. I've found a way to unit test Firestore by mocking it using the cloud firestore mocks package at dart pub. So far I've been trying to search if there were any equivalents for Firebase Realtime Database and I haven't seen any. Both here and Google..
So my question is, how would one be able to create a unit test that needs a Mock of a FirebaseDatabase instance? similar to how you could do it in the mock firestore package so that I can do something like:
MockDbInstance mockFirebaseDatabaseInstance = MockFirebaseDatabaseInstance();
await mockFirebaseDatabaseInstance.reference().child("this_node").setValue(myObject);
Update:
We couldn't find a way to easily test RTDB so we decided to move all our data to FireStore.
Upvotes: 0
Views: 1895
Reputation: 1486
I wrote a fireabase_database_mocks package which mock firebase real time database but it is incomplete it does not support the simulation of events like onChildAdded for now but it's doable. Here is an example of using fireabase_database_mocks :
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database_mocks/firebase_database_mocks.dart';
import 'package:flutter_test/flutter_test.dart';
class UserRepository {
UserRepository(this.firebaseDatabase);
FirebaseDatabase firebaseDatabase;
Future<String> getUserName(String userId) async {
final userNameReference =
firebaseDatabase.reference().child('users').child(userId).child('name');
final dataSnapshot = await userNameReference.once();
return dataSnapshot.value;
}
Future<Map<String, dynamic>> getUser(String userId) async {
final userNode = firebaseDatabase.reference().child('users/$userId');
final dataSnapshot = await userNode.once();
return dataSnapshot.value;
}
}
void main() {
FirebaseDatabase firebaseDatabase;
UserRepository userRepository;
// Put fake data
const userId = 'userId';
const userName = 'Elon musk';
const fakeData = {
'users': {
userId: {
'name': userName,
'email': '[email protected]',
'photoUrl': 'url-to-photo.jpg',
},
'otherUserId': {
'name': 'userName',
'email': '[email protected]',
'photoUrl': 'other_url-to-photo.jpg',
}
}
};
MockFirebaseDatabase.instance.reference().set(fakeData);
setUp(() {
firebaseDatabase = MockFirebaseDatabase.instance;
userRepository = UserRepository(firebaseDatabase);
});
test('Should get userName ...', () async {
final userNameFromFakeDatabase = await userRepository.getUserName(userId);
expect(userNameFromFakeDatabase, equals(userName));
});
test('Should get user ...', () async {
final userNameFromFakeDatabase = await userRepository.getUser(userId);
expect(
userNameFromFakeDatabase,
equals({
'name': userName,
'email': '[email protected]',
'photoUrl': 'url-to-photo.jpg',
}),
);
});
}
Upvotes: 4