패키지, 저장소 및 앱 카테고리 검색

패키지 상세v4.5.0

fake_cloud_firestore

이전에 cloud_firestore_mocks로 알려져 있었습니다. Cloud Firestore의 가짜 구현입니다. Cloud Firestore를 사용하는 앱의 단위 테스트에 이 패키지를 사용하세요.

AndroidiOSWebmacOSWindows
30일 다운로드
30.7만
좋아요
147
Pub 점수
150

패키지 설치

flutter pub add fake_cloud_firestore

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Flutter 애플리케이션의 단위 테스트를 위한 Cloud Firestore의 가짜 구현입니다. 실제 Cloud Firestore 서비스의 동작을 모방하여 실제 Firebase 백엔드가 필요 없이 앱의 데이터 로직을 테스트할 수 있게 해줍니다. 이 패키지는 테스트를 격리하고 개발 중에 일관되고 반복 가능한 결과를 보장하는 데 이상적입니다. 원래는 cloud_firestore_mocks로 알려졌으며, Android, iOS, Web, macOS 및 Windows를 포함한 모든 주요 플랫폼을 지원합니다.

사용 사례

  • Firestore에 의존하는 로직의 단위 테스트
  • 실시간 Firebase 연결 없이 앱 상태 테스트하기
  • 통합 테스트 중 구성 요소 분리
  • 테스트에서 다양한 Firestore 응답 시뮬레이션
  • 배포 전 데이터 처리 검증

주요 기능

  • Cloud Firestore API 완전 호환
  • 모든 주요 Flutter 플랫폼을 지원합니다
  • 테스트 환경을 위한 간편한 설정
  • 모킹된 문서 및 컬렉션 작업
  • Firebase 프로젝트 구성이 필요하지 않습니다

적합한 대상

  • Flutter 개발자가 단위 테스트 작성 중
  • 테스트 신뢰성을 우선시하는 팀
  • 복잡한 Firestore 상호작용을 가진 프로젝트
  • 테스트에서 실제 Firebase 비용을 회피하는 개발자
  • 결정론적 테스트 결과가 필요한 앱

고려 사항

  • 엔드 투 엔드 테스트에 적합하지 않습니다
  • 실시간 동기화 동작을 복제하지 않습니다
  • 클라이언트 측 로직 테스트에 제한
  • 초기 데이터의 수동 설정이 필요합니다
  • 실제 Firestore의 모든 에지 케이스를 반영하지 않을 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Fake Cloud Firestore

pub package Unit Tests Buy Me A Coffee

Fakes to write unit tests for Cloud Firestore. Instantiate a FakeFirebaseFirestore, then pass it around your project as if it were a FirebaseFirestore. This Fake acts like Firestore except that will only keep the data in memory. To help debug, you can use FakeFirebaseFirestore.dump() to see what's in the fake database. This is useful to set up the state of your database, then check that your UI behaves the way you expect.

This project works well with firebase_auth_mocks. If you use them together, you can even test your app with security rules. See below.

Usage

Simple example
import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';

void main() {
  final instance = FakeFirebaseFirestore();
  await instance.collection('users').add({
    'username': 'Bob',
  });
  final snapshot = await instance.collection('users').get();
  print(snapshot.docs.length); // 1
  print(snapshot.docs.first.get('username')); // 'Bob'
  print(instance.dump());
}

// Prints out:
// {
//   "users": {
//     "z": {
//       "name": "Bob"
//     }
//   }
// }

See more examples at fake_cloud_firestore/test/fake_cloud_firestore_test.dart.

In a UI test
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
import 'package:firestore_example/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

const MessagesCollection = 'messages';

void main() {
  testWidgets('shows messages', (WidgetTester tester) async {
    // Populate the fake database.
    final firestore = FakeFirebaseFirestore();
    await firestore.collection(MessagesCollection).add({
      'message': 'Hello world!',
      'created_at': FieldValue.serverTimestamp(),
    });

    // Render the widget.
    await tester.pumpWidget(MaterialApp(
        title: 'Firestore Example', home: MyHomePage(firestore: firestore)));
    // Let the snapshots stream fire a snapshot.
    await tester.idle();
    // Re-render.
    await tester.pump();
    // // Verify the output.
    expect(find.text('Hello world!'), findsOneWidget);
    expect(find.text('Message 1 of 1'), findsOneWidget);
  });
}

See more examples at fake_cloud_firestore/example/test/widget_test.dart.

Exceptions
Based on the state

Most features automatically throw exceptions depending on the state, so you do not need to mock them. For example, calling DocumentSnapshot.get on a missing field will throw a StateError.

final firestore = FakeFirebaseFirestore();
final collection = firestore.collection('test');
final doc = collection.doc('test');
await doc.set({
  'nested': {'field': 3}
});

final snapshot = await doc.get();

expect(() => snapshot.get('foo'), throwsA(isA<StateError>()));
expect(() => snapshot.get('nested.foo'), throwsA(isA<StateError>()));
Mocking exceptions

Furthermore, some methods allow mocking exceptions manually, for example to simulate network errors. You can even set conditions on the parameters using the standard Dart matchers. Here are the methods which support mocking exceptions:

  • DocumentReference.get, set, update, delete.
  • Query.get.
final instance = FakeFirebaseFirestore();
final doc = instance.collection('users').doc(uid);
whenCalling(Invocation.method(#set, null))
    .on(doc)
    .thenThrow(FirebaseException(plugin: 'firestore'));
expect(() => doc.set({'name': 'Bob'}), throwsA(isA<FirebaseException>()));

For examples of how to set conditions on when to throw an exception, see firebase_auth_mocks#throwing-exceptions.

Security Rules

You can pass the security rules that you use in production in Firestore to [FakeFirebaseFirestore]. When operating on [DocumentReference] using get, set, update, or delete, [FakeFirebaseFirestore] will then check security rules and throw exceptions if access is restricted. In the example below, we restrict users/{userId} documents to their respective owners. Before they sign in, they cannot access any document inside the users collection. Once they sign in, they have access to only their own users/[uid] document.

import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
import 'package:firebase_auth_mocks/firebase_auth_mocks.dart';
import 'package:test/test.dart';

// https://firebase.google.com/docs/rules/rules-and-auth#leverage_user_information_in_rules
final authUidDescription = '''
service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}''';

main() async {
  test('security rules' {
    final auth = MockFirebaseAuth();
    final firestore = FakeFirebaseFirestore(
        // Pass security rules to restrict `/users/{user}` documents.
        securityRules: authUidDescription,
        // Make MockFirebaseAuth inform FakeFirebaseFirestore of sign-in
        // changes.
        authObject: auth.authForFakeFirestore);
    // The user signs-in. FakeFirebaseFirestore knows about it thanks to
    // `authObject`.
    await auth.signInWithCustomToken('some token');
    final uid = auth.currentUser!.uid;
    // Now the user can access their user-specific document.
    expect(
        () => firestore.doc('users/$uid').set({'name': 'abc'}), returnsNormally);
    // But not anyone else's.
    expect(() => firestore.doc('users/abcdef').set({'name': 'abc'}),
        throwsException);
  });
}

See https://github.com/atn832/fake_cloud_firestore/blob/master/test/security_test.dart for more examples of security rules.

Right now we only support operations on DocumentReference. Later we will implement security checks for batch requests, collections and queries. Furthermore, we do not support timestamps and durations yet. See Fake Firebase Rules for an exhaustive list of what is and is not supported.

Resetting security rules

You can also dynamically change the security rules. This is useful if you want to first set up data without any restriction, then apply security rules for the actual tests.

https://github.com/atn832/fake_cloud_firestore/blob/0bd0b648241c0ed3e6eac2c26eef85135e3e47f9/test/security_test.dart#L82-L85

Features

  • Dump the state of the fake firebase with FakeFirebaseFirestore.dump().
  • Clear the fake firebase with FakeFirebaseFirestore.clearPersistence().
  • Create documents and collections.
  • Supports Converters.
  • Create documents with collection.add or document.set.
  • Batch writes and runTransaction.
  • Query documents with collection.snapshots or query.get.
  • Queries:
    • Filter results with query.where. The library supports equals, isGreaterThan, isGreaterThanOrEqualTo, isLessThan,isLessThanOrEqualTo, isNull, isNotEqualTo, arrayContains, arrayContainsAny, whereIn and whereNotIn.
    • Supports filtering by special fields like FieldPath.documentId and __name__.
    • Sort results with query.orderBy.
    • Limit results with query.limit, limitToLast, startAfterDocument, startAt, startAtDocument, endAt, endAtDocument, endBefore, endBeforeDocument. Note: startAnd and endAt work only on exact matches.
    • Filter with Filter, including composite filters like Filter.and and Filter.or.
    • Aggregate with query.count, query.aggregate(sum(field1), average(field2)...).
  • ValueField:
    • set timestamps with FieldValue.serverTimestamp(). Optionally you can pass a Clock when instantiating FakeFirebaseFirestore to define what time gets set.
    • delete values with FieldValue.delete().
    • update numerical values with FieldValue.increment.
    • update arrays with FieldValue.arrayUnion and FieldValue.arrayRemove.
  • Mock exceptions for DocumentReference.set.
  • Security rules:
    • Initialize FakeFirebaseFirestore with custom security rules.
    • FakeFirebaseFirestore takes authentication state from firebase_auth_mocks into account.
    • Reset security rules.
    • DocumentReference.get, set, update and delete are protected.

Compatibility table

cloud_firestore fake_cloud_firestore
6.7.1 4.2.0
6.2.0 4.1.0
6.0.0 4.0.0
5.0.0 3.0.0
4.17.0 2.5.0
4.4.0 2.4.0
4.0.0 2.0.0
3.4.0 1.3.0
3.0.0 1.2.1
2.2.0 1.1.0
2.1.0 1.0.2
1.0.0 0.8.4
0.16.0 0.6.0
0.14.0 0.5.0
0.13.1+1 0.4.1
0.13.0+1 0.2.5
^0.12.9+6 0.2.0

Features and bugs

Please file feature requests and bugs at the issue tracker.

카테고리

의존성

의존성 목록 10 개

소스 저장소

이 패키지를 사용하는 프로젝트