Skip to content

Commit cdcfbde

Browse files
committed
2 parents 70679d5 + 60e7676 commit cdcfbde

File tree

1 file changed

+69
-3
lines changed

1 file changed

+69
-3
lines changed

README.md

Lines changed: 69 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,76 @@
11
# firebase_database_mocks
2+
Fakes to write unit tests for FirebaseDatabase (real-time database). Get Instance
3+
`MockFirebaseDatabase.instance`, then pass it around your project as if it were a
4+
`FirebaseDatabase.instance`. This mock keep data in memory while test running.
25

3-
A new Flutter project.
6+
## Usage
7+
```dart
8+
import 'package:firebase_database/firebase_database.dart';
9+
import 'package:firebase_database_mocks/firebase_database_mocks.dart';
10+
import 'package:flutter_test/flutter_test.dart';
411
5-
## Getting Started
12+
class UserRepository {
13+
UserRepository(this.firebaseDatabase);
14+
FirebaseDatabase firebaseDatabase;
615
7-
This project is a starting point for a Flutter application.
16+
Future<String> getUserName(String userId) async {
17+
final userNameReference =
18+
firebaseDatabase.reference().child('users').child(userId).child('name');
19+
final dataSnapshot = await userNameReference.once();
20+
return dataSnapshot.value;
21+
}
22+
23+
Future<Map<String, dynamic>> getUser(String userId) async {
24+
final userNode = firebaseDatabase.reference().child('users/$userId');
25+
final dataSnapshot = await userNode.once();
26+
return dataSnapshot.value;
27+
}
28+
}
29+
30+
void main() {
31+
FirebaseDatabase firebaseDatabase;
32+
UserRepository userRepository;
33+
// Put fake data
34+
const userId = 'userId';
35+
const userName = 'Elon musk';
36+
const fakeData = {
37+
'users': {
38+
userId: {
39+
'name': userName,
40+
'email': '[email protected]',
41+
'photoUrl': 'url-to-photo.jpg',
42+
},
43+
'otherUserId': {
44+
'name': 'userName',
45+
'email': '[email protected]',
46+
'photoUrl': 'other_url-to-photo.jpg',
47+
}
48+
}
49+
};
50+
MockFirebaseDatabase.instance.reference().set(fakeData);
51+
setUp(() {
52+
firebaseDatabase = MockFirebaseDatabase.instance;
53+
userRepository = UserRepository(firebaseDatabase);
54+
});
55+
test('Should get userName ...', () async {
56+
final userNameFromFakeDatabase = await userRepository.getUserName(userId);
57+
expect(userNameFromFakeDatabase, equals(userName));
58+
});
59+
60+
test('Should get user ...', () async {
61+
final userNameFromFakeDatabase = await userRepository.getUser(userId);
62+
expect(
63+
userNameFromFakeDatabase,
64+
equals({
65+
'name': userName,
66+
'email': '[email protected]',
67+
'photoUrl': 'url-to-photo.jpg',
68+
}),
69+
);
70+
});
71+
}
72+
73+
```
874

975
A few resources to get you started if this is your first Flutter project:
1076

0 commit comments

Comments
 (0)