firebase_database_mock 0.1.0 icon indicating copy to clipboard operation
firebase_database_mock: ^0.1.0 copied to clipboard

Mocks to write unit tests for FirebaseDatabase (real-time database).

firebase_database_mocks #

Pub Version style: effective dart test: passing

Mocks library to write unit tests for FirebaseDatabase (real-time database). Get Instance MockFirebaseDatabase.instance, then pass it around your project as if it was a FirebaseDatabase.instance. This mock keep data in memory while test running.

Usage #

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 {
  FirebaseDatabase firebaseDatabase;

  Future<String> getUserName(String userId) async {
    final userNameReference =
    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': '',
        'photoUrl': 'url-to-photo.jpg',
      'otherUserId': {
        'name': 'userName',
        'email': '',
        'photoUrl': 'other_url-to-photo.jpg',
  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);
        'name': userName,
        'email': '',
        'photoUrl': 'url-to-photo.jpg',

As you can see you don't need to initialize firabase core for testing or call TestWidgetsFlutterBinding.ensureInitialized() before using MockFirebaseDatabase but in bonus if you use another firebase service that needs it you can simply call the setupFirebaseMocks() top level function which performs all required operations for testing a firebase service that isn't fully mocked .

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

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.