<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Victor Eronmosele's Blog]]></title><description><![CDATA[A highly motivated software engineer especially experienced as a mobile team lead working with diverse teams from all over the globe. He enjoys building secure,]]></description><link>https://blog.victoreronmosele.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 09 Nov 2026 02:56:54 GMT</lastBuildDate><atom:link href="https://blog.victoreronmosele.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Mocking and Testing Firestore Operations in Flutter Unit Tests | Part 2 (Transactions and Batched Writes)]]></title><description><![CDATA[In this article, Victor Eronmosele examines how to unit test operations involving Transactions and Batched Writes in Flutter.]]></description><link>https://blog.victoreronmosele.com/mocking-firestore-flutter-2</link><guid isPermaLink="true">https://blog.victoreronmosele.com/mocking-firestore-flutter-2</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Firebase]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Victor Eronmosele]]></dc:creator><pubDate>Tue, 15 Mar 2022 12:09:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647346103528/ljjOXimp3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Introduction</h1>
<p>Firestore offers the ability to perform atomic operations — <a href="https://en.wikipedia.org/wiki/Atomicity_(database_systems)">"series of database operations such that either all occurs, or nothing occurs"</a> — in form of Transactions and Batched Writes.</p>
<blockquote>
<p>Transactions: a transaction is a set of read and write operations on one or more documents.</p>
<p>Batched Writes: a batched write is a set of write operations on one or more documents.</p>
<p>Source: <a href="https://firebase.google.com/docs/firestore/manage-data/transactions">Firebase Documentation for Transactions and Batched Writes</a></p>
</blockquote>
<p>This article examines how to write unit tests for Firestore Transactions and Batched Writes in Flutter.</p>
<p>We continue from the last article: <a href="https://blog.victoreronmosele.com/mocking-firestore-flutter">Mocking and Testing Firestore Operations in Flutter Unit Tests | Part 1 (Documents and Collections)</a> where we looked at how to implement unit tests for Firestore operations involving Documents and Collections.</p>
<p>The article was created using <code>Flutter Channel stable, 2.8.1</code>.</p>
<h1>Prerequisites</h1>
<p>The prerequisites are the same as in the previous article.</p>
<p>Add the following packages to your <code>pubspec.yaml</code> file and run <code>flutter pub get</code>.</p>
<pre><code class="language-yaml">dependencies:
  ...
  cloud_firestore: ^3.1.4
  fake_cloud_firestore: ^1.2.0

dev_dependencies:
  ...
  test:
</code></pre>
<p>This adds <code>cloud_firestore</code> which is the Cloud Firestore package, <code>fake_cloud_firestore</code> which is the mock Firestore package and <code>test</code> which is the package used for unit tests.</p>
<h1>Problem Statement</h1>
<p>We extend our <code>FirestoreService</code> class from the previous article — which performed read and write operations to Firestore using Documents and Collections — to perform read and write operations to Firestore using Transactions and Batched Writes and we want to write a set of unit tests for this class.</p>
<p>The class is shown below (with the Document and Collection part removed for readability):</p>
<pre><code class="language-dart">import 'package:cloud_firestore/cloud_firestore.dart';

class FirestoreService {
  const FirestoreService({required this.firestore});

  final FirebaseFirestore firestore;

  // Document and Collection operations removed for readability

  Future&lt;void&gt; runTransaction({
    required Map&lt;String, dynamic&gt; dataToUpdate,
    required Map&lt;String, dynamic&gt; dataToSet,
    required String collectionPath,
    required String documentPathToUpdate,
    required String documentPathToSetTo,
    required String documentPathToDelete,
  }) async {
    return firestore.runTransaction&lt;void&gt;((transaction) async {
      final DocumentReference documentReferenceToUpdate =
          firestore.collection(collectionPath).doc(documentPathToUpdate);
      final DocumentReference documentReferenceToSetTo =
          firestore.collection(collectionPath).doc(documentPathToSetTo);
      final DocumentReference documentReferenceToDelete =
          firestore.collection(collectionPath).doc(documentPathToDelete);

      final DocumentSnapshot documentSnapshotForUpdate =
          await transaction.get(documentReferenceToUpdate);

      final Map&lt;String, dynamic&gt; dataInDocumentPathToUpdate =
          documentSnapshotForUpdate.data() as Map&lt;String, dynamic&gt;;

      final Map&lt;String, dynamic&gt; updatedData = {
        ...dataInDocumentPathToUpdate,
        ...dataToUpdate
      };

      transaction.update(documentReferenceToUpdate, updatedData);

      transaction.set(documentReferenceToSetTo, dataToSet);

      transaction.delete(documentReferenceToDelete);
    });
  }

  Future&lt;void&gt; runBatchedWrite({
    required Map&lt;String, dynamic&gt; dataToSet,
    required Map&lt;String, dynamic&gt; dataToUpdate,
    required String collectionPath,
    required String documentPathToSetTo,
    required String documentPathToUpdate,
    required String documentPathToDelete,
  }) async {
    final WriteBatch writeBatch = firestore.batch();

    final CollectionReference collectionReference =
        firestore.collection(collectionPath);

    final DocumentReference documentReferenceToSetTo =
        collectionReference.doc(documentPathToSetTo);
    final DocumentReference documentReferenceToUpdate =
        collectionReference.doc(documentPathToUpdate);
    final DocumentReference documentReferenceToDelete =
        collectionReference.doc(documentPathToDelete);

    writeBatch.set(documentReferenceToSetTo, dataToSet);

    writeBatch.update(documentReferenceToUpdate, dataToUpdate);

    writeBatch.delete(documentReferenceToDelete);

    await writeBatch.commit();
  }
}
</code></pre>
<h1>Understanding The Methods</h1>
<p>This section helps understand the <code>runTransaction</code> and the <code>runBatchedWrite</code> methods with regards to what is expected for unit testing them.</p>
<h3>runTransaction</h3>
<pre><code class="language-dart"> Future&lt;void&gt; runTransaction({
    required Map&lt;String, dynamic&gt; dataToUpdate,
    required Map&lt;String, dynamic&gt; dataToSet,
    required String collectionPath,
    required String documentPathToUpdate,
    required String documentPathToSetTo,
    required String documentPathToDelete,
  }) async {
    return firestore.runTransaction&lt;void&gt;((transaction) async {
      final DocumentReference documentReferenceToUpdate =
          firestore.collection(collectionPath).doc(documentPathToUpdate);
      final DocumentReference documentReferenceToSetTo =
          firestore.collection(collectionPath).doc(documentPathToSetTo);
      final DocumentReference documentReferenceToDelete =
          firestore.collection(collectionPath).doc(documentPathToDelete);

      final DocumentSnapshot documentSnapshotForUpdate =
          await transaction.get(documentReferenceToUpdate);

      final Map&lt;String, dynamic&gt; dataInDocumentPathToUpdate =
          documentSnapshotForUpdate.data() as Map&lt;String, dynamic&gt;;

      final Map&lt;String, dynamic&gt; updatedData = {
        ...dataInDocumentPathToUpdate,
        ...dataToUpdate
      };

      transaction.update(documentReferenceToUpdate, updatedData);

      transaction.set(documentReferenceToSetTo, dataToSet);

      transaction.delete(documentReferenceToDelete);
    });
  }
</code></pre>
<p>The <code>runTransaction</code> method demonstrates how to do transactions in Firestore. Since transactions allow you to perform read operations and writes operations, the <code>runTransaction</code> method has both read and write operations in it.</p>
<p>The major operations in this method are below:</p>
<ul>
<li><p>The transaction reads the data at <code>documentPathToUpdate</code> and merges it with <code>dataToUpdate</code> and updates the document there.</p>
</li>
<li><p>The transaction sets <code>dataToSet</code> to the document at the <code>documentPathToSetTo</code>.</p>
</li>
<li><p>The transaction deletes the document at <code>documentPathToDelete</code>.</p>
</li>
</ul>
<h3>runBatchedWrite</h3>
<pre><code class="language-dart"> Future&lt;void&gt; runBatchedWrite({
   required Map&lt;String, dynamic&gt; dataToSet,
   required Map&lt;String, dynamic&gt; dataToUpdate,
   required String collectionPath,
   required String documentPathToSetTo,
   required String documentPathToUpdate,
   required String documentPathToDelete,
 }) async {
   final WriteBatch writeBatch = firestore.batch();

   final CollectionReference collectionReference =
       firestore.collection(collectionPath);

   final DocumentReference documentReferenceToSetTo =
       collectionReference.doc(documentPathToSetTo);
   final DocumentReference documentReferenceToUpdate =
       collectionReference.doc(documentPathToUpdate);
   final DocumentReference documentReferenceToDelete =
       collectionReference.doc(documentPathToDelete);

   writeBatch.set(documentReferenceToSetTo, dataToSet);

   writeBatch.update(documentReferenceToUpdate, dataToUpdate);

   writeBatch.delete(documentReferenceToDelete);

   await writeBatch.commit();
 }
</code></pre>
<p>The <code>runBatchedWrite</code> method demonstrates how to perform batched writes in Firestore. Since batched writes allow you to perform only write operations, the <code>runBatchedWrite</code> method contains only write operations.</p>
<p>The major operations in this method are below:</p>
<ul>
<li><p>The batched write updates the document at <code>documentPathToUpdate</code> with <code>dataToUpdate</code>.</p>
</li>
<li><p>The batched write sets <code>dataToSet</code> to the document at the <code>documentPathToSetTo</code>.</p>
</li>
<li><p>The batched write deletes the document at <code>documentPathToDelete</code>.</p>
</li>
</ul>
<h1>Testing Approach</h1>
<p>Just as it was outlined in the <a href="https://blog.victoreronmosele.com/mocking-firestore-flutter#heading-testing-approach">previous article</a>, we do the following to test the methods:</p>
<ul>
<li><p><em>Construction Injection</em>:</p>
<p>The <code>FakeFirebaseFirestore</code> object is passed into the <code>FirestoreService</code> instance to mock the <code>FirebaseFirestore</code> object.</p>
</li>
<li><p><em>Mocking Strategy &amp; Database State Set Up</em>:</p>
<p>Data is added to specific document/collection paths in the <code>FakeFirebaseFirestore</code> object before carrying out the operation in the <code>FirestoreService</code> class.</p>
<p>Data is then retrieved from the <code>FakeFirebaseFirestore</code> object at specific paths to compare them with the expected values by asserting that they are the same.</p>
</li>
</ul>
<p>The two methods above, individually, contain different read and/or write operations and those are the operations that will be tested.</p>
<p>The tests will be written in the same test file from the <a href="https://blog.victoreronmosele.com/mocking-firestore-flutter#heading-testing-approach">previous article</a></p>
<h1>Testing the Transactions and Batched Writes class</h1>
<h3>Test For Running A Transaction</h3>
<h4><em>runTransaction's Test</em></h4>
<p>The runTransaction method can be tested by:</p>
<ul>
<li><p>Injecting the mock Firestore object, <code>fakeFirebaseFirestore</code>, to the service.</p>
</li>
<li><p>Prepopulating the document at <code>documentPathToUpdate</code> via the fakeFirebaseFirestore object with the <code>data</code> object.</p>
</li>
<li><p>Prepopulating the document at <code>documentPathToDelete</code> via the fakeFirebaseFirestore object with the <code>data</code> object.</p>
</li>
<li><p>Running the <code>runTransaction</code> method and passing <code>dataToUpdateWith</code> and <code>dataToSet</code> which will be used by the method to write to <code>documentPathToUpdate</code> and <code>documentPathToSetTo</code>.</p>
</li>
<li><p>Retrieving the actual data contained in the <code>documentPathToUpdate</code>, <code>documentPathToSetTo</code> and <code>documentPathToDelete</code> document paths.</p>
</li>
<li><p>Asserting that the data in <code>documentPathToUpdate</code> is equal to the expected updated data, <code>expectedUpdatedData</code> i.e <code>dataToUpdateWith</code> merged with <code>data</code>.</p>
</li>
<li><p>Asserting that the data in <code>documentPathToSetTo</code> is equal to the expected set data i.e <code>dataToSet</code>.</p>
</li>
<li><p>Asserting that the data in <code>documentPathToDelete</code> is null.</p>
</li>
</ul>
<p>This is shown below:</p>
<pre><code class="language-dart"> test('runTransaction runs the correct transaction operation', () async {
  final FirestoreService firestoreService =
      FirestoreService(firestore: fakeFirebaseFirestore!);

  const String collectionPath = 'collectionPath';
  const String documentPathToUpdate = 'documentPathToUpdate';
  const String documentPathToSetTo = 'documentPathToSetTo';
  const String documentPathToDelete = 'documentPathToDelete';

  final CollectionReference collectionReference =
      fakeFirebaseFirestore!.collection(collectionPath);

  final DocumentReference documentReferenceToUpdate =
      collectionReference.doc(documentPathToUpdate);
  final DocumentReference documentReferenceToSetTo =
      collectionReference.doc(documentPathToSetTo);
  final DocumentReference documentReferenceToDelete =
      collectionReference.doc(documentPathToDelete);

  documentReferenceToUpdate.set(data);
  documentReferenceToDelete.set(data);

  const Map&lt;String, dynamic&gt; dataToUpdateWith = {'updated_data': '43'};
  const Map&lt;String, dynamic&gt; dataToSet = {'data': 44};

  const Map&lt;String, dynamic&gt; expectedUpdatedData = {
    ...data,
    ...dataToUpdateWith
  };

  await firestoreService.runTransaction(
      dataToUpdate: dataToUpdateWith,
      dataToSet: dataToSet,
      collectionPath: collectionPath,
      documentPathToUpdate: documentPathToUpdate,
      documentPathToSetTo: documentPathToSetTo,
      documentPathToDelete: documentPathToDelete);

  final DocumentSnapshot documentSnapshotForUpdate =
      await documentReferenceToUpdate.get();
  final DocumentSnapshot documentSnapshotForSet =
      await documentReferenceToSetTo.get();
  final DocumentSnapshot documentSnapshotForDelete =
      await documentReferenceToDelete.get();

  final actualDataFromUpdate = documentSnapshotForUpdate.data();
  final actualDataFromSet = documentSnapshotForSet.data();
  final actualDataFromDelete = documentSnapshotForDelete.data();

  expect(actualDataFromUpdate, expectedUpdatedData);
  expect(actualDataFromSet, dataToSet);
  expect(actualDataFromDelete, null);
});
</code></pre>
<h3>Test For Running A Batched Write</h3>
<h4><em>runBatchedWrite's Test</em></h4>
<p>The runBatchedWrite method can be tested by:</p>
<ul>
<li><p>Injecting the mock Firestore object, <code>fakeFirebaseFirestore</code>, to the service.</p>
</li>
<li><p>Prepopulating the document at <code>documentPathToUpdate</code> via the fakeFirebaseFirestore object with the <code>data</code> object.</p>
</li>
<li><p>Prepopulating the document at <code>documentPathToDelete</code> via the fakeFirebaseFirestore object with the <code>data</code> object.</p>
</li>
<li><p>Running the <code>runBatchedWrite</code> method and passing <code>dataToUpdateWith</code> and <code>dataToSet</code> which will be used by the method to write to <code>documentPathToUpdate</code> and <code>documentPathToSetTo</code>.</p>
</li>
<li><p>Retrieving the actual data contained in the <code>documentPathToUpdate</code>, <code>documentPathToSetTo</code> and <code>documentPathToDelete</code> document paths.</p>
</li>
<li><p>Asserting that the data in <code>documentPathToUpdate</code> is equal to the expected updated data, <code>expectedUpdatedData</code> i.e <code>dataToUpdateWith</code> merged with <code>data</code>.</p>
</li>
<li><p>Asserting that the data in <code>documentPathToSetTo</code> is equal to the expected set data i.e <code>dataToSet</code>.</p>
</li>
<li><p>Asserting that the data in <code>documentPathToDelete</code> is null.</p>
</li>
</ul>
<p>This is shown below:</p>
<pre><code class="language-dart"> test('runBatchedWrite runs the correct batched write operation',
    () async {
  final FirestoreService firestoreService =
      FirestoreService(firestore: fakeFirebaseFirestore!);
  const String collectionPath = 'collectionPath';
  const String documentPathToUpdate = 'documentPathToUpdate';
  const String documentPathToSetTo = 'documentPathToSetTo';
  const String documentPathToDelete = 'documentPathToDelete';

  final CollectionReference collectionReference =
      fakeFirebaseFirestore!.collection(collectionPath);

  final DocumentReference documentReferenceToUpdate =
      collectionReference.doc(documentPathToUpdate);
  final DocumentReference documentReferenceToSetTo =
      collectionReference.doc(documentPathToSetTo);
  final DocumentReference documentReferenceToDelete =
      collectionReference.doc(documentPathToDelete);

  documentReferenceToUpdate.set(data);
  documentReferenceToDelete.set(data);

  const Map&lt;String, dynamic&gt; dataToUpdateWith = {'updated_data': '43'};
  const Map&lt;String, dynamic&gt; dataToSet = {'data': 44};

  const Map&lt;String, dynamic&gt; expectedUpdatedData = {
    ...data,
    ...dataToUpdateWith
  };

  await firestoreService.runBatchedWrite(
      dataToUpdate: dataToUpdateWith,
      dataToSet: dataToSet,
      collectionPath: collectionPath,
      documentPathToUpdate: documentPathToUpdate,
      documentPathToSetTo: documentPathToSetTo,
      documentPathToDelete: documentPathToDelete);

  final DocumentSnapshot documentSnapshotForUpdate =
      await documentReferenceToUpdate.get();
  final DocumentSnapshot documentSnapshotForSet =
      await documentReferenceToSetTo.get();
  final DocumentSnapshot documentSnapshotForDelete =
      await documentReferenceToDelete.get();

  final actualDataFromUpdate = documentSnapshotForUpdate.data();
  final actualDataFromSet = documentSnapshotForSet.data();
  final actualDataFromDelete = documentSnapshotForDelete.data();

  expect(actualDataFromUpdate, expectedUpdatedData);
  expect(actualDataFromSet, dataToSet);
  expect(actualDataFromDelete, null);
});
</code></pre>
<h1>Complete Test File</h1>
<p>The content of the entire test file is shown below:</p>
<pre><code class="language-dart">import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
import 'package:firestore_unit_test_flutter/firestore_service.dart';
import 'package:flutter/foundation.dart';
import 'package:test/test.dart';

void main() {
  group('FirestoreService', () {
    FakeFirebaseFirestore? fakeFirebaseFirestore;
    const Map&lt;String, dynamic&gt; data = {'data': '42'};

    setUp(() {
      fakeFirebaseFirestore = FakeFirebaseFirestore();
    });

    // Document operations and Collection operations tests removed for readability

    group('Transaction Operation', () {
      test('runTransaction runs the correct transaction operation', () async {
        final FirestoreService firestoreService =
            FirestoreService(firestore: fakeFirebaseFirestore!);

        const String collectionPath = 'collectionPath';
        const String documentPathToUpdate = 'documentPathToUpdate';
        const String documentPathToSetTo = 'documentPathToSetTo';
        const String documentPathToDelete = 'documentPathToDelete';

        final CollectionReference collectionReference =
            fakeFirebaseFirestore!.collection(collectionPath);

        final DocumentReference documentReferenceToUpdate =
            collectionReference.doc(documentPathToUpdate);
        final DocumentReference documentReferenceToSetTo =
            collectionReference.doc(documentPathToSetTo);
        final DocumentReference documentReferenceToDelete =
            collectionReference.doc(documentPathToDelete);

        documentReferenceToUpdate.set(data);
        documentReferenceToDelete.set(data);

        const Map&lt;String, dynamic&gt; dataToUpdateWith = {'updated_data': '43'};
        const Map&lt;String, dynamic&gt; dataToSet = {'data': 44};

        const Map&lt;String, dynamic&gt; expectedUpdatedData = {
          ...data,
          ...dataToUpdateWith
        };

        await firestoreService.runTransaction(
            dataToUpdate: dataToUpdateWith,
            dataToSet: dataToSet,
            collectionPath: collectionPath,
            documentPathToUpdate: documentPathToUpdate,
            documentPathToSetTo: documentPathToSetTo,
            documentPathToDelete: documentPathToDelete);

        final DocumentSnapshot documentSnapshotForUpdate =
            await documentReferenceToUpdate.get();
        final DocumentSnapshot documentSnapshotForSet =
            await documentReferenceToSetTo.get();
        final DocumentSnapshot documentSnapshotForDelete =
            await documentReferenceToDelete.get();

        final actualDataFromUpdate = documentSnapshotForUpdate.data();
        final actualDataFromSet = documentSnapshotForSet.data();
        final actualDataFromDelete = documentSnapshotForDelete.data();

        expect(actualDataFromUpdate, expectedUpdatedData);
        expect(actualDataFromSet, dataToSet);
        expect(actualDataFromDelete, null);
      });
    });

    group('Batched Write Operation', () {
      test('runBatchedWrite runs the correct batched write operation',
          () async {
        final FirestoreService firestoreService =
            FirestoreService(firestore: fakeFirebaseFirestore!);
        const String collectionPath = 'collectionPath';
        const String documentPathToUpdate = 'documentPathToUpdate';
        const String documentPathToSetTo = 'documentPathToSetTo';
        const String documentPathToDelete = 'documentPathToDelete';

        final CollectionReference collectionReference =
            fakeFirebaseFirestore!.collection(collectionPath);

        final DocumentReference documentReferenceToUpdate =
            collectionReference.doc(documentPathToUpdate);
        final DocumentReference documentReferenceToSetTo =
            collectionReference.doc(documentPathToSetTo);
        final DocumentReference documentReferenceToDelete =
            collectionReference.doc(documentPathToDelete);

        documentReferenceToUpdate.set(data);
        documentReferenceToDelete.set(data);

        const Map&lt;String, dynamic&gt; dataToUpdateWith = {'updated_data': '43'};
        const Map&lt;String, dynamic&gt; dataToSet = {'data': 44};

        const Map&lt;String, dynamic&gt; expectedUpdatedData = {
          ...data,
          ...dataToUpdateWith
        };

        await firestoreService.runBatchedWrite(
            dataToUpdate: dataToUpdateWith,
            dataToSet: dataToSet,
            collectionPath: collectionPath,
            documentPathToUpdate: documentPathToUpdate,
            documentPathToSetTo: documentPathToSetTo,
            documentPathToDelete: documentPathToDelete);

        final DocumentSnapshot documentSnapshotForUpdate =
            await documentReferenceToUpdate.get();
        final DocumentSnapshot documentSnapshotForSet =
            await documentReferenceToSetTo.get();
        final DocumentSnapshot documentSnapshotForDelete =
            await documentReferenceToDelete.get();

        final actualDataFromUpdate = documentSnapshotForUpdate.data();
        final actualDataFromSet = documentSnapshotForSet.data();
        final actualDataFromDelete = documentSnapshotForDelete.data();

        expect(actualDataFromUpdate, expectedUpdatedData);
        expect(actualDataFromSet, dataToSet);
        expect(actualDataFromDelete, null);
      });
    });
  });
}

// MapListContains Matcher code removed for readability
</code></pre>
<h1>Conclusion</h1>
<p>This article demonstrates how to write unit tests for Firebase Firestore's atomic operations, that is, Transactions and Batched Writes.</p>
<p>The complete code can be found on <a href="https://github.com/victoreronmosele/firestore-unit-test-flutter">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Mocking and Testing Firestore Operations in Flutter Unit Tests | Part 1 (Documents and Collections)]]></title><description><![CDATA[This article examines Firestore operations with respect to Documents and Collections and demonstrates how to mock and test them. The article was created…]]></description><link>https://blog.victoreronmosele.com/mocking-firestore-flutter</link><guid isPermaLink="true">https://blog.victoreronmosele.com/mocking-firestore-flutter</guid><category><![CDATA[Firebase]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Testing]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[Dart]]></category><dc:creator><![CDATA[Victor Eronmosele]]></dc:creator><pubDate>Tue, 15 Feb 2022 00:57:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1644886416938/-SE6rnxW0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Introduction</h1>
<p>This article examines <a href="https://firebase.google.com/docs/firestore">Firestore</a> operations with respect to Documents and Collections and demonstrates how to mock and test them.</p>
<p>The article was created using <code>Flutter Channel stable, 2.8.1</code>.</p>
<h1>Prerequisites</h1>
<p>Add the following packages to your <code>pubspec.yaml</code> file and run <code>flutter pub get</code>.</p>
<pre><code class="language-yaml">dependencies:
  ...
  cloud_firestore: ^3.1.4

dev_dependencies:
  ...
  test:
  fake_cloud_firestore: ^1.2.0
</code></pre>
<p>This adds <code>cloud_firestore</code> which is the Cloud Firestore package, <code>test</code> which is the package used for unit tests and <code>fake_cloud_firestore</code> which is the mock Firestore package.</p>
<h1>Problem Statement</h1>
<p>We have a class <code>FirestoreService</code> which performs read and write operations to Firestore and we want to write a set of unit tests for this class.</p>
<p>The class is shown below:</p>
<pre><code class="language-dart">import 'package:cloud_firestore/cloud_firestore.dart';

class FirestoreService {
  const FirestoreService({required this.firestore});

  final FirebaseFirestore firestore;

  /// Collection Operations

  Future&lt;DocumentReference&lt;Map&lt;String, dynamic&gt;&gt;&gt; addToCollection(
      {required Map&lt;String, dynamic&gt; data,
      required String collectionPath}) async {
    return firestore.collection(collectionPath).add(data);
  }

  Future&lt;QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt; getFromCollection(
      {required String collectionPath}) {
    return firestore.collection(collectionPath).get();
  }

  Stream&lt;QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt; getSnapshotStreamFromCollection(
      {required String collectionPath}) {
    return firestore.collection(collectionPath).snapshots();
  }

  /// Document Operations

  Future&lt;void&gt; deleteDocumentFromCollection(
      {required String collectionPath, required String documentPath}) async {
    return firestore.collection(collectionPath).doc(documentPath).delete();
  }

  Future&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt; getFromDocument(
      {required String collectionPath, required String documentPath}) {
    return firestore.collection(collectionPath).doc(documentPath).get();
  }

  Future&lt;void&gt; setDataOnDocument(
      {required Map&lt;String, dynamic&gt; data,
      required String collectionPath,
      required String documentPath}) {
    return firestore.collection(collectionPath).doc(documentPath).set(data);
  }

  Stream&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt; getSnapshotStreamFromDocument(
      {required String collectionPath, required String documentPath}) {
    return firestore.collection(collectionPath).doc(documentPath).snapshots();
  }

  Future&lt;void&gt; updateDataOnDocument(
      {required Map&lt;String, dynamic&gt; data,
      required String collectionPath,
      required String documentPath}) {
    return firestore.collection(collectionPath).doc(documentPath).update(data);
  }
}
</code></pre>
<h1>Testing Approach</h1>
<h3>Construction Injection</h3>
<p>Since the class <code>FirestoreService</code> injects the <code>Firestore</code> object through its constructor, we can pass the <code>FakeFirebaseFirestore</code> object from the <code>fake_cloud_firestore</code> package and use that to test the methods in the class.</p>
<h3>Mocking Strategy</h3>
<p>The <code>FakeFirebaseFirestore</code> object works like the <code>Firestore</code> object and the read and write operations that can be used to retrieve and add data to the <code>Firestore</code> object can also be used to retrieve and add data to the <code>FakeFirebaseFirestore</code> object.</p>
<p>This helps us prepopulate the mock object right before we call our methods and helps confirm the expected state of the <code>Firestore</code> database.</p>
<h3>Database State Set Up</h3>
<h4><em>Initial State</em></h4>
<p>The initial state of the <code>FakeFirebaseFirestore</code> object can be set up by calling the regular write operations on the <code>CollectionReference</code> and <code>DocumentReference</code>.</p>
<p>For instance, we want the initial state of the database to have an object <code>{answer: 42}</code> written to a document <code>lifeTheUniverseAndEverything</code> in collection <code>answers</code>, we write the code below to set it up:</p>
<pre><code class="language-dart"> final FakeFirebaseFirestore fakeFirebaseFirestore = FakeFirebaseFirestore();

 const String collectionPath = 'answers';
 const String documentPath = 'lifeTheUniverseAndEverything';

 const Map&lt;String, dynamic&gt; data = {'answer': 42};

 await fakeFirebaseFirestore
        .collection(collectionPath)
        .doc(documentPath)
        .set(data);
</code></pre>
<h4><em>Final State</em></h4>
<p>The final state of the <code>FakeFirebaseFirestore</code> object can be gotten by calling the regular read operations on the <code>CollectionReference</code> and <code>DocumentReference</code>.</p>
<p>Now, to get the final state of the <code>FakeFirebaseFirestore</code> object from above, we write the code below:</p>
<pre><code class="language-dart"> final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; documentSnapshot =
        await fakeFirebaseFirestore
            .collection(collectionPath)
            .doc(documentPath)
            .get();
 final Map&lt;String, dynamic&gt; actualData = documentSnapshot.data()!;

 print(actualData); // {'answer': 42}
</code></pre>
<h4><em>Assertion</em></h4>
<p>Once we have our data, our database's initial state set up and the final state retrieved, we can assert that the data in the database matches the expected data.</p>
<p>Going by what we have above, we can write the assertion using the test package's <code>expect</code> method like below:</p>
<pre><code class="language-dart">expect(actualData, data);  /// Passes ✅
</code></pre>
<h1>Testing The FirestoreService Class</h1>
<p>We will test the <code>FirestoreService</code> class by following the approach described in the <code>Testing Approach</code> section above.</p>
<p>This section will be divided into three:</p>
<ul>
<li><p>Set-up (where the objects needed for the tests are created)</p>
</li>
<li><p>Collection Operations Testing (where operations involving Collections are tested)</p>
</li>
<li><p>Document Operations Testing (where operations involving Documents are tested)</p>
</li>
</ul>
<h3>Set-up</h3>
<p>Create a test file <code>firestore_service_test.dart</code> and add the following code to it:</p>
<pre><code class="language-dart">import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
import 'package:test/test.dart';

void main() {
  group('FirestoreService', () {
    FakeFirebaseFirestore? fakeFirebaseFirestore;
    const Map&lt;String, dynamic&gt; data = {'data': '42'};

    setUp(() {
      fakeFirebaseFirestore = FakeFirebaseFirestore();
    });
  });
}
</code></pre>
<p>This creates the <code>FakeFirebaseFirestore</code> object and the data needed for every test we'll write for the <code>FirestoreService</code> class. All of the tests are put inside the "FirestoreService" group.</p>
<h3>Collection Operations Testing</h3>
<h4><em>Map Equality</em></h4>
<p>This section will be testing Collection operations and this means we will be asserting that the collection contains the data. Typically, that is done by using the <a href="https://api.flutter.dev/flutter/package-matcher_matcher/contains.html">contains</a> matcher.</p>
<blockquote>
<p>Returns a matcher that matches if the match argument contains the expected value.</p>
</blockquote>
<p>This is how an assertion using the <code>contains</code> matcher would be written:</p>
<pre><code class="language-dart"> final List&lt;int&gt; intList = [1, 2];
 final int intData = 2;

 expect(intList, contains(intData));  /// Passes ✅
 ```

This passes but when it comes to Lists of Maps, it's a different case. 

The assertion below fails:

```dart
final List&lt;Map&lt;String, dynamic&gt;&gt; mapList = [
     {'data': 42}
];
final mapData = {'data': 42};
expect(mapList, contains(mapData)); /// Fails ❌
</code></pre>
<p>This is because the <code>contains</code> matcher for Lists is implemented this way:</p>
<pre><code class="language-dart">return item.contains(_expected);
</code></pre>
<p>which in turn uses the <code>contains</code> method on List which is implemented like below:</p>
<pre><code class="language-dart">bool contains(Object? element) {
  for (E e in this) {
    if (e == element) return true;
  }
  return false;
}
</code></pre>
<p>The code above checks that the <code>e</code> object is the same object as the <code>element</code> object. And the <code>mapData</code> object won't be the same as the one contained in the List. That explains why the test fails.</p>
<h4><em>mapEquals</em></h4>
<p>In order to get around this, we can make use of the <a href="https://api.flutter.dev/flutter/foundation/mapEquals.html">mapEquals</a> function that does the following:</p>
<blockquote>
<p>Compares two maps for element-by-element equality.</p>
<p>Returns true if the maps are both null, or if they are both non-null, they have the same lengths and they contain the same keys associated with the same values. Returns false otherwise.</p>
</blockquote>
<p>We can check if any of the element in the list is equal to the <code>mapData</code> object by using the <code>mapEquals</code> function like this:</p>
<pre><code class="language-dart">final List&lt;Map&lt;String, dynamic&gt;&gt; mapList = [
        {'data': 42}
];
final mapData = {'data': 42};
expect(mapList.any((element) =&gt; mapEquals(element, mapData)), true); /// Passes ✅
</code></pre>
<p>This test passes because the equality check using <code>mapEquals</code> compares the two Map objects by confirming that the keys and values are the same.</p>
<h4><em>Custom Matcher</em></h4>
<p>While using the check above would work for our tests, it's cleaner and more readable to follow the Flutter convention of using a Matcher to assert our test.</p>
<p>We move the logic <code>mapList.any((element) =&gt; mapEquals(element, mapData))</code> into the Matcher like this below:</p>
<pre><code class="language-dart">class MapListContains extends Matcher {
  final Map&lt;dynamic, dynamic&gt; _expected;

  const MapListContains(this._expected);

  @override
  Description describe(Description description) {
    return description.add('contains ').addDescriptionOf(_expected);
  }

  @override
  bool matches(dynamic item, Map matchState) {
    if (item is List&lt;Map&gt;) {
      return item.any((element) =&gt; mapEquals(element, _expected));
    }
    return false;
  }
}
</code></pre>
<p>The <code>MapListContains</code> class extends the <code>Matcher</code> abstract class and overrides the <code>describe</code> method and the <code>matches</code> method. The assertion logic is implemented in the <code>matches</code> method in the <code>MapListContains</code> class.</p>
<p>So we can update the test to this below:</p>
<pre><code class="language-dart">final List&lt;Map&lt;String, dynamic&gt;&gt; mapList = [
        {'data': 42}
];
final mapData = {'data': 42};
expect(mapList, MapListContains(mapData));  /// Passes ✅
</code></pre>
<p>And this test passes.</p>
<h4><em>Set-up</em></h4>
<p>Now, we move to the actual test set-up.</p>
<p>We first create a group "Collection Operations" to hold tests for collection operations.</p>
<pre><code class="language-dart">import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
import 'package:test/test.dart';

void main() {
  group('FirestoreService', () {
    FakeFirebaseFirestore? fakeFirebaseFirestore;
    const Map&lt;String, dynamic&gt; data = {'data': '42'};

    setUp(() {
       fakeFirebaseFirestore = FakeFirebaseFirestore();
    });

    group('Collection Operations', () {

    });
  });
 }
</code></pre>
<p>We, can add each test inside of the group.</p>
<h4><em>Test For Adding To A Collection.</em></h4>
<pre><code class="language-dart">Future&lt;DocumentReference&lt;Map&lt;String, dynamic&gt;&gt;&gt; addToCollection(
   {required Map&lt;String, dynamic&gt; data,
    required String collectionPath}) async {
  return firestore.collection(collectionPath).add(data);
}
</code></pre>
<p>The <code>addToCollection</code> method above can be tested by:</p>
<ul>
<li><p>Injecting the mock Firestore object, <code>fakeFirebaseFirestore</code>, to the service.</p>
</li>
<li><p>Adding the data to the collection via the service's <code>addToCollection</code> method.</p>
</li>
<li><p>Retrieving the actual data list in the collection via <code>fakeFirebaseFirestore</code>.</p>
</li>
<li><p>Asserting that the actual data list contains the added data using the <code>MapListContains</code> matcher.</p>
</li>
</ul>
<p>This is shown below:</p>
<pre><code class="language-dart">test('addToCollection adds data to given collection', () async {
    final FirestoreService firestoreService =
           FirestoreService(firestore: fakeFirebaseFirestore!);
    const String collectionPath = 'collectionPath';

    await firestoreService.addToCollection(
           data: data, collectionPath: collectionPath);

    final List&lt;Map&lt;String, dynamic&gt;&gt; actualDataList =
           (await fakeFirebaseFirestore!.collection('collectionPath').get())
               .docs
               .map((e) =&gt; e.data())
               .toList();

    expect(actualDataList, const MapListContains(data));  /// Passes ✅
});
</code></pre>
<h4><em>Test For Getting Data From A Collection.</em></h4>
<p>Future&lt;QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt; getFromCollection() { return firestore.collection('collectionPath').get(); }</p>
<pre><code class="language-plaintext">
The `getFromCollection` method above can be tested by:
- Injecting the mock Firestore object, `fakeFirebaseFirestore`,  to the service.
- Adding the data to the collection via the `fakeFirebaseFirestore` object.
- Retrieving the actual data list in the collection via the service's `getFromCollection` method.
- Asserting that the data list contains the added data using the `MapListContains` matcher.

This is shown below:

```dart
test('getFromCollection gets data from a given collection', () async {
   final FirestoreService firestoreService =
           FirestoreService(firestore: fakeFirebaseFirestore!);
   const String collectionPath = 'collectionPath';

   await fakeFirebaseFirestore!.collection(collectionPath).add(data);

   final List&lt;Map&lt;String, dynamic&gt;&gt; dataList = (await firestoreService
               .getFromCollection(collectionPath: collectionPath))
           .docs
           .map((e) =&gt; e.data())
           .toList();

   expect(dataList, const MapListContains(data)); /// Passes ✅
});
</code></pre>
<h4><em>Test For Getting A Snapshot Stream From A Collection.</em></h4>
<p>Stream&lt;QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt; getSnapshotStreamFromCollection( {required String collectionPath}) { return firestore.collection(collectionPath).snapshots(); }</p>
<pre><code class="language-plaintext">
The `getSnapshotStreamFromCollection` method above can be tested by:
- Injecting the mock Firestore object, `fakeFirebaseFirestore`,  to the service
- Adding the data to the collection via the `fakeFirebaseFirestore` object.
- Retrieving the expected snapshot stream from the `fakeFirebaseFirestore` object and the actual snapshot stream from the service's `getSnapshotStreamFromCollection` method.
- Getting the data from the two snapshot streams and putting them into individual lists (the actual data list and the expected data list).
- Asserting that the actual data list is equal to the expected data list.

This is shown below:

```dart
test( 'getSnapshotStreamFromCollection returns a stream of QuerySnaphot containing the data added', () async {
    final FirestoreService firestoreService =
           FirestoreService(firestore: fakeFirebaseFirestore!);
    const String collectionPath = 'collectionPath';

    final CollectionReference&lt;Map&lt;String, dynamic&gt;&gt; collectionReference =
           fakeFirebaseFirestore!.collection(collectionPath);
    await collectionReference.add(data);

    final Stream&lt;QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt;
           expectedSnapshotStream = collectionReference.snapshots();

    final actualSnapshotStream = firestoreService
           .getSnapshotStreamFromCollection(collectionPath: collectionPath);

    final QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt; expectedQuerySnapshot =
           await expectedSnapshotStream.first;
    final QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualQuerySnapshot =
           await actualSnapshotStream.first;

    final List&lt;Map&lt;String, dynamic&gt;&gt; expectedDataList =
           expectedQuerySnapshot.docs.map((e) =&gt; e.data()).toList();
    final List&lt;Map&lt;String, dynamic&gt;&gt; actualDataList =
           actualQuerySnapshot.docs.map((e) =&gt; e.data()).toList();

    expect(actualDataList, expectedDataList); /// Passes ✅
});
</code></pre>
<h3>Document Operations Testing</h3>
<h4><em>Test For Deleting A Document From A Collection.</em></h4>
<pre><code class="language-dart">Future&lt;void&gt; deleteDocumentFromCollection(
   {required String collectionPath, required String documentPath}) async {
 return firestore.collection(collectionPath).doc(documentPath).delete();
}
</code></pre>
<p>The <code>deleteDocumentFromCollection</code> method above can be tested by:</p>
<ul>
<li><p>Injecting the mock Firestore object, <code>fakeFirebaseFirestore</code>, to the service.</p>
</li>
<li><p>Adding the data to the collection via the <code>fakeFirebaseFirestore</code> object.</p>
</li>
<li><p>Deleting the document at the collection via the service's <code>deleteDocumentFromCollection</code> method.</p>
</li>
<li><p>Getting the data at the document's path from the <code>fakeFirebaseFirestore</code>.</p>
</li>
<li><p>Asserting that the document does not exist.</p>
</li>
</ul>
<p>This is shown below:</p>
<p>test('deleteDocumentFromCollection deletes a document from a given collection', () async { final FirestoreService firestoreService = FirestoreService(firestore: fakeFirebaseFirestore!); const String collectionPath = 'collectionPath';</p>
<pre><code class="language-plaintext">    final CollectionReference&lt;Map&lt;String, dynamic&gt;&gt; collectionReference =
        fakeFirebaseFirestore!.collection(collectionPath);

    final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
        await collectionReference.add(data);

    final String documentPath = documentReference.path;

    await firestoreService.deleteDocumentFromCollection(
        collectionPath: collectionPath, documentPath: documentPath);

    final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; documentSnapshot =
        await collectionReference.doc(documentPath).get();

    expect(documentSnapshot.exists, false); /// Passes ✅
  });
</code></pre>
<pre><code class="language-plaintext">- #### *Test For Getting A Document's Data.* 
```dart
Future&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt; getFromDocument(
   {required String collectionPath, required String documentPath}) {
 return firestore.collection(collectionPath).doc(documentPath).get();
}
</code></pre>
<p>The <code>getFromDocument</code> method above can be tested by:</p>
<ul>
<li><p>Injecting the mock Firestore object, <code>fakeFirebaseFirestore</code>, to the service.</p>
</li>
<li><p>Setting data to the document via the <code>fakeFirebaseFirestore</code> object.</p>
</li>
<li><p>Retrieving the actual data in the document via the service's <code>getFromDocument</code> method.</p>
</li>
<li><p>Asserting that the data retrieved via the service is equal to the data set via <code>fakeFirebaseFirestore</code>.</p>
</li>
</ul>
<p>This is shown below: ```dart test('getFromDocument gets data from a given document', () async { final FirestoreService firestoreService = FirestoreService(firestore: fakeFirebaseFirestore!);</p>
<pre><code class="language-plaintext">    const String collectionPath = 'collectionPath';
    const String documentPath = 'documentPath';

    final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
        fakeFirebaseFirestore!.collection(collectionPath).doc(documentPath);

    await documentReference.set(data);

    final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; expectedDocumentSnapshot =
        await documentReference.get();

    final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualDocumentSnapshot =
        await firestoreService.getFromDocument(
            collectionPath: collectionPath, documentPath: documentPath);

    final Map&lt;String, dynamic&gt;? expectedData =
        expectedDocumentSnapshot.data();
    final Map&lt;String, dynamic&gt;? actualData = actualDocumentSnapshot.data();

    expect(actualData, expectedData); /// Passes ✅
  });
</code></pre>
<pre><code class="language-plaintext">
- #### *Test For Setting Documents's Data.* 
```dart
Future&lt;void&gt; setDataOnDocument(
   {required Map&lt;String, dynamic&gt; data,
   required String collectionPath,
   required String documentPath}) {
 return firestore.collection(collectionPath).doc(documentPath).set(data);
}
</code></pre>
<p>The <code>setDataOnDocument</code> method above can be tested by:</p>
<ul>
<li><p>Injecting the mock Firestore object, <code>fakeFirebaseFirestore</code>, to the service.</p>
</li>
<li><p>Setting data to the document via the service's <code>setDataOnDocument</code> method.</p>
</li>
<li><p>Retrieving the actual data in the document via the <code>fakeFirebaseFirestore</code> object.</p>
</li>
<li><p>Asserting that the data set via the service is equal to the data retrieved via <code>fakeFirebaseFirestore</code>.</p>
</li>
</ul>
<p>This is shown below:</p>
<pre><code class="language-dart">test('setDataOnDocument sets data on a given document', () async {
     final FirestoreService firestoreService =
         FirestoreService(firestore: fakeFirebaseFirestore!);

     const String collectionPath = 'collectionPath';
     const String documentPath = 'documentPath';

     await firestoreService.setDataOnDocument(
         data: data,
         collectionPath: collectionPath,
         documentPath: documentPath);

     final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
         fakeFirebaseFirestore!.collection(collectionPath).doc(documentPath);

     final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualDocumentSnapshot =
         await documentReference.get();
     final Map&lt;String, dynamic&gt;? actualData = actualDocumentSnapshot.data();

     const Map&lt;String, dynamic&gt; expectedData = data;

     expect(actualData, expectedData); /// Passes ✅
   });
</code></pre>
<h4><em>Test For Getting A Snapshot Stream From A Document.</em></h4>
<pre><code class="language-dart">Stream&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt; getSnapshotStreamFromDocument(
   {required String collectionPath, required String documentPath}) {
 return firestore.collection(collectionPath).doc(documentPath).snapshots();
}
</code></pre>
<p>The <code>getSnapshotStreamFromDocument</code> method above can be tested by:</p>
<ul>
<li><p>Injecting the mock Firestore object, <code>fakeFirebaseFirestore</code>, to the service.</p>
</li>
<li><p>Setting the data to the document via the <code>fakeFirebaseFirestore</code> object.</p>
</li>
<li><p>Retrieving the expected snapshot stream from the <code>fakeFirebaseFirestore</code> object and the actual snapshot stream from the service's <code>getSnapshotStreamFromDocument</code> method.</p>
</li>
<li><p>Getting the data from the two snapshot streams.</p>
</li>
<li><p>Asserting that the actual data via the service is equal to the expected data via <code>fakeFirebaseFirestore</code>.</p>
</li>
</ul>
<p>This is shown below:</p>
<p>test( 'getSnapshotStreamFromDocument returns a stream of DocumentSnapshot containing the data set', () async { final FirestoreService firestoreService = FirestoreService(firestore: fakeFirebaseFirestore!);</p>
<pre><code class="language-plaintext">    const String collectionPath = 'collectionPath';
    const String documentPath = 'documentPath';

    final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
        fakeFirebaseFirestore!.collection(collectionPath).doc(documentPath);

    await documentReference.set(data);

    final Stream&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt;
        expectedSnapshotStream = documentReference.snapshots();

    final Stream&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt;
        actualSnapshotStream =
        firestoreService.getSnapshotStreamFromDocument(
            collectionPath: collectionPath, documentPath: documentPath);

    final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; expectedDocumentSnapshot =
        await expectedSnapshotStream.first;
    final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualDocumentSnapshot =
        await actualSnapshotStream.first;

    final Map&lt;String, dynamic&gt;? expectedData =
        expectedDocumentSnapshot.data();
    final Map&lt;String, dynamic&gt;? actualData = actualDocumentSnapshot.data();

    expect(actualData, expectedData); /// Passes ✅
  });
</code></pre>
<pre><code class="language-plaintext">
- #### *Test For Updating A Document's Data.* 
```dart
Future&lt;void&gt; updateDataOnDocument(
   {required Map&lt;String, dynamic&gt; data,
   required String collectionPath,
   required String documentPath}) {
 return firestore.collection(collectionPath).doc(documentPath).update(data);
}
</code></pre>
<p>The <code>updateDataOnDocument</code> method above can be tested by: - Injecting the mock Firestore object, <code>fakeFirebaseFirestore</code>, to the service. - Setting data to the document via the <code>fakeFirebaseFirestore</code> object. - Updating the data set to the document via the service's <code>updateDataOnDocument</code> method. - Retrieving the data in the document via <code>fakeFirebaseStore</code>. - Asserting that the updated data set via the service is equal to the expected data retrieved via <code>fakeFirebaseFirestore</code>.</p>
<p>This is shown below:</p>
<pre><code class="language-dart">test('updateDataOnDocument updates a given document\'s data', () async {
  final FirestoreService firestoreService =
         FirestoreService(firestore: fakeFirebaseFirestore!);

  const String collectionPath = 'collectionPath';
  const String documentPath = 'documentPath';

  final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
         fakeFirebaseFirestore!.collection(collectionPath).doc(documentPath);

  await documentReference.set(data);

  final Map&lt;String, dynamic&gt; dataUpdate = {'data': '43'};

  await firestoreService.updateDataOnDocument(
         data: dataUpdate,
         collectionPath: collectionPath,
         documentPath: documentPath);

  final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualDocumentSnapshot =
         await documentReference.get();

  final Map&lt;String, dynamic&gt;? actualData = actualDocumentSnapshot.data();

  final Map&lt;String, dynamic&gt; expectedData = dataUpdate;

  expect(actualData, expectedData); /// Passes ✅
}); 
</code></pre>
<h1>Complete Test File</h1>
<p>The content of the entire test file is shown below:</p>
<pre><code class="language-dart">import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
import 'package:firestore_unit_test_flutter/firestore_service.dart';
import 'package:flutter/foundation.dart';
import 'package:test/test.dart';

void main() {
  group('FirestoreService', () {
    FakeFirebaseFirestore? fakeFirebaseFirestore;
    const Map&lt;String, dynamic&gt; data = {'data': '42'};

    setUp(() {
      fakeFirebaseFirestore = FakeFirebaseFirestore();
    });

    group(
      'Collection Operations',
      () {
        test('addToCollection adds data to given collection', () async {
          final FirestoreService firestoreService =
              FirestoreService(firestore: fakeFirebaseFirestore!);
          const String collectionPath = 'collectionPath';

          await firestoreService.addToCollection(
              data: data, collectionPath: collectionPath);

          final List&lt;Map&lt;String, dynamic&gt;&gt; actualDataList =
              (await fakeFirebaseFirestore!.collection('collectionPath').get())
                  .docs
                  .map((e) =&gt; e.data())
                  .toList();

          expect(actualDataList, const MapListContains(data));
        });

        test('getFromCollection gets data from a given collection', () async {
          final FirestoreService firestoreService =
              FirestoreService(firestore: fakeFirebaseFirestore!);
          const String collectionPath = 'collectionPath';

          await fakeFirebaseFirestore!.collection(collectionPath).add(data);

          final List&lt;Map&lt;String, dynamic&gt;&gt; dataList = (await firestoreService
                  .getFromCollection(collectionPath: collectionPath))
              .docs
              .map((e) =&gt; e.data())
              .toList();

          expect(dataList, const MapListContains(data));
        });

        test(
            'getSnapshotStreamFromCollection returns a stream of QuerySnaphot containing the data added',
            () async {
          final FirestoreService firestoreService =
              FirestoreService(firestore: fakeFirebaseFirestore!);
          const String collectionPath = 'collectionPath';

          final CollectionReference&lt;Map&lt;String, dynamic&gt;&gt; collectionReference =
              fakeFirebaseFirestore!.collection(collectionPath);
          await collectionReference.add(data);

          final Stream&lt;QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt;
              expectedSnapshotStream = collectionReference.snapshots();

          final actualSnapshotStream = firestoreService
              .getSnapshotStreamFromCollection(collectionPath: collectionPath);

          final QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt; expectedQuerySnapshot =
              await expectedSnapshotStream.first;
          final QuerySnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualQuerySnapshot =
              await actualSnapshotStream.first;

          final List&lt;Map&lt;String, dynamic&gt;&gt; expectedDataList =
              expectedQuerySnapshot.docs.map((e) =&gt; e.data()).toList();
          final List&lt;Map&lt;String, dynamic&gt;&gt; actualDataList =
              actualQuerySnapshot.docs.map((e) =&gt; e.data()).toList();

          expect(actualDataList, expectedDataList);
        });
      },
    );

    group('Document Operations', () {
      test(
          'deleteDocumentFromCollection deletes a document from a given collection',
          () async {
        final FirestoreService firestoreService =
            FirestoreService(firestore: fakeFirebaseFirestore!);
        const String collectionPath = 'collectionPath';

        final CollectionReference&lt;Map&lt;String, dynamic&gt;&gt; collectionReference =
            fakeFirebaseFirestore!.collection(collectionPath);

        final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
            await collectionReference.add(data);

        final String documentPath = documentReference.path;

        await firestoreService.deleteDocumentFromCollection(
            collectionPath: collectionPath, documentPath: documentPath);

        final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; documentSnapshot =
            await collectionReference.doc(documentPath).get();

        expect(documentSnapshot.exists, false);
      });

      test('getFromDocument gets data from a given document', () async {
        final FirestoreService firestoreService =
            FirestoreService(firestore: fakeFirebaseFirestore!);

        const String collectionPath = 'collectionPath';
        const String documentPath = 'documentPath';

        final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
            fakeFirebaseFirestore!.collection(collectionPath).doc(documentPath);

        await documentReference.set(data);

        final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; expectedDocumentSnapshot =
            await documentReference.get();

        final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualDocumentSnapshot =
            await firestoreService.getFromDocument(
                collectionPath: collectionPath, documentPath: documentPath);

        final Map&lt;String, dynamic&gt;? expectedData =
            expectedDocumentSnapshot.data();
        final Map&lt;String, dynamic&gt;? actualData = actualDocumentSnapshot.data();

        expect(actualData, expectedData);
      });

      test('setDataOnDocument sets data on a given document', () async {
        final FirestoreService firestoreService =
            FirestoreService(firestore: fakeFirebaseFirestore!);

        const String collectionPath = 'collectionPath';
        const String documentPath = 'documentPath';

        await firestoreService.setDataOnDocument(
            data: data,
            collectionPath: collectionPath,
            documentPath: documentPath);

        final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
            fakeFirebaseFirestore!.collection(collectionPath).doc(documentPath);

        final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualDocumentSnapshot =
            await documentReference.get();
        final Map&lt;String, dynamic&gt;? actualData = actualDocumentSnapshot.data();

        const Map&lt;String, dynamic&gt; expectedData = data;

        expect(actualData, expectedData);
      });

      test(
          'getSnapshotStreamFromDocument returns a stream of DocumentSnapshot containing the data set',
          () async {
        final FirestoreService firestoreService =
            FirestoreService(firestore: fakeFirebaseFirestore!);

        const String collectionPath = 'collectionPath';
        const String documentPath = 'documentPath';

        final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
            fakeFirebaseFirestore!.collection(collectionPath).doc(documentPath);

        await documentReference.set(data);

        final Stream&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt;
            expectedSnapshotStream = documentReference.snapshots();

        final Stream&lt;DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;&gt;
            actualSnapshotStream =
            firestoreService.getSnapshotStreamFromDocument(
                collectionPath: collectionPath, documentPath: documentPath);

        final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; expectedDocumentSnapshot =
            await expectedSnapshotStream.first;
        final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualDocumentSnapshot =
            await actualSnapshotStream.first;

        final Map&lt;String, dynamic&gt;? expectedData =
            expectedDocumentSnapshot.data();
        final Map&lt;String, dynamic&gt;? actualData = actualDocumentSnapshot.data();

        expect(actualData, expectedData);
      });

      test('updateDataOnDocument updates a given document\'s data', () async {
        final FirestoreService firestoreService =
            FirestoreService(firestore: fakeFirebaseFirestore!);

        const String collectionPath = 'collectionPath';
        const String documentPath = 'documentPath';

        final DocumentReference&lt;Map&lt;String, dynamic&gt;&gt; documentReference =
            fakeFirebaseFirestore!.collection(collectionPath).doc(documentPath);

        await documentReference.set(data);

        final Map&lt;String, dynamic&gt; dataUpdate = {'data': '43'};

        await firestoreService.updateDataOnDocument(
            data: dataUpdate,
            collectionPath: collectionPath,
            documentPath: documentPath);

        final DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt; actualDocumentSnapshot =
            await documentReference.get();

        final Map&lt;String, dynamic&gt;? actualData = actualDocumentSnapshot.data();

        final Map&lt;String, dynamic&gt; expectedData = dataUpdate;

        expect(actualData, expectedData);
      });
    });
  });
}

class MapListContains extends Matcher {
  final Map&lt;dynamic, dynamic&gt; _expected;

  const MapListContains(this._expected);

  @override
  Description describe(Description description) {
    return description.add('contains ').addDescriptionOf(_expected);
  }

  @override
  bool matches(dynamic item, Map matchState) {
    if (item is List&lt;Map&gt;) {
      return item.any((element) =&gt; mapEquals(element, _expected));
    }
    return false;
  }
}
</code></pre>
<h1>Conclusion</h1>
<p>This article demonstrates how to unit test Firebase Firestore operations involving Collections and Documents. It also shows how to use a custom Matcher in test assertions.</p>
<p>The complete code can be found on <a href="https://github.com/victoreronmosele/firestore-unit-test-flutter">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Mocking and Testing Shared Preferences in Flutter Unit Tests]]></title><description><![CDATA[This article demonstrates how to unit-test Shared Preferences in Flutter projects. This article assumes that the reader is familiar with Flutter…]]></description><link>https://blog.victoreronmosele.com/mocking-shared-preferences-flutter</link><guid isPermaLink="true">https://blog.victoreronmosele.com/mocking-shared-preferences-flutter</guid><category><![CDATA[unit testing]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Dart]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Victor Eronmosele]]></dc:creator><pubDate>Mon, 06 Dec 2021 10:48:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1638787624495/Ar1uW___JO.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Introduction</h1>
<p>This article demonstrates how to unit-test <a href="https://pub.dev/packages/shared_preferences">Shared Preferences</a> in Flutter projects.</p>
<p>This article assumes that the reader is familiar with Flutter development and the Dart language.</p>
<p>The code in the demo was created using <code>Flutter Channel stable, 2.5.3</code>.</p>
<h1>Problem Statement</h1>
<p>We have a <code>SharedPreferencesUtil</code> class that makes use of the <code>SharedPreferences</code> object to store and retrieve an integer <code>count</code>. Our task is to unit-test the methods of this class.</p>
<p>The class is shown below:</p>
<pre><code class="language-dart">import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesUtil {
  SharedPreferencesUtil({required this.sharedPreferences});

  final SharedPreferences sharedPreferences;

  @visibleForTesting
  static const String countKey = 'counter';

  int getCount() {
    return sharedPreferences.getInt(countKey) ?? 0;
  }

  Future&lt;bool&gt; setCount(int count) async {
    return sharedPreferences.setInt(countKey, count);
  }
}
</code></pre>
<h1>Testing the methods</h1>
<p>In the <code>SharedPreferencesUtil</code> class above, the <code>SharedPreferences</code> object is passed through the constructor and it is used in the following methods:</p>
<ul>
<li><p><code>getCount()</code>: To return the value of the count integer stored in <code>SharedPreferences</code> with the <code>countKey</code> key and return 0 if the value in <code>SharedPreferences</code> is <code>null</code></p>
</li>
<li><p><code>setCount()</code>: To set the value of count int with the <code>countKey</code> key in <code>SharedPreferences</code></p>
</li>
</ul>
<p>In order to write a test, we need to mock the <code>SharedPreferences</code> object that we pass into the <code>SharedPreferencesUtil</code> class.</p>
<p>This is done using the <a href="https://pub.dev/documentation/shared_preferences/latest/shared_preferences/SharedPreferences/setMockInitialValues.html">SharedPreferences.setMockInitialValues()</a> static method.</p>
<h2>setMockInitialValues()</h2>
<p>Initializes the shared preferences with mock values for testing.</p>
<p><a href="https://pub.dev/documentation/shared_preferences/latest/shared_preferences/SharedPreferences/setMockInitialValues.html">Source</a></p>
<p>This method is used to mock the initial state of the <code>SharedPreferences</code> object used in tests. It takes a parameter of type <code>Map&lt;String, Object&gt;</code> for which the key is used to identify the stored <code>SharedPreferences</code> object and the value is the actual object stored in <code>SharedPreferences</code>.</p>
<p>For instance:</p>
<p>If we want our <code>SharedPreferences</code> object in our test to store the number 42 with the key <code>counter</code>, we do it this way:</p>
<pre><code class="language-dart">SharedPreferences.setMockInitialValues({'counter': 42});
</code></pre>
<h2>Testing the getCounter() method</h2>
<ul>
<li><p><em>Test that the</em> <code>getCount()</code> <em>method returns 0 if there is no value stored in</em> <code>SharedPreferences</code><em>.</em></p>
<p>We first call the <code>SharedPreferences.setMockInitialValues()</code> and pass it <code>{}</code> (empty <code>Map</code> object) method to make sure nothing is stored in <code>SharedPreferences</code>. We, then, pass it into the <code>SharedPreferencesUtil</code> class.</p>
<p>We, then, can call the <code>getCount()</code> method and compare it with the expected value of 0 using the <a href="https://pub.dev/documentation/test_api/latest/expect/expect.html">expect()</a> method from the test library.</p>
</li>
</ul>
<pre><code class="language-plaintext">import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_unit_tests_flutter/shared_preferences_util.dart';
import 'package:test/test.dart';

main() {
  group(SharedPreferencesUtil, () {
    group('getCounter', () {
      test('returns 0 if no value is stored in SharedPreferences', () async {
        SharedPreferences.setMockInitialValues({});

        final SharedPreferences sharedPreferences =
            await SharedPreferences.getInstance();

        final SharedPreferencesUtil sharedPreferencesUtil =
            SharedPreferencesUtil(sharedPreferences: sharedPreferences);

        const expectedCounter = 0;
        final actualCounter = sharedPreferencesUtil.getCount();

        expect(expectedCounter, actualCounter);
      });
    });
  });
}
</code></pre>
<ul>
<li><p><em>Test that the</em> <code>getCount()</code> <em>method returns the correct value stored in</em> <code>SharedPreferences</code><em>.</em></p>
<p>We first call <code>SharedPreferences.setMockInitialValues()</code> and pass it <code>{SharedPreferencesUtil.countKey: counterValue}</code> where <code>SharedPreferencesUtil.counterKey</code> is the key and <code>counterValue</code> contains the value we want to store. We, then, pass it into the <code>SharedPreferencesUtil</code> class.</p>
<p>We, then, can call the <code>getCount()</code> method and compare it with the expected value of 0 using the <code>expect()</code> method.</p>
</li>
</ul>
<pre><code class="language-dart">import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_unit_tests_flutter/shared_preferences_util.dart';
import 'package:test/test.dart';

main() {
  group(SharedPreferencesUtil, () {
    group('getCounter', () {
      test('returns 0 if no value is stored in SharedPreferences', () async {
       ...
      });

      test('returns the correct value stored in SharedPreferences', () async {
        const counterValue = 42;
        SharedPreferences.setMockInitialValues(
            {SharedPreferencesUtil.countKey: counterValue});
        final SharedPreferences sharedPreferences =
            await SharedPreferences.getInstance();

        final SharedPreferencesUtil sharedPreferencesUtil =
            SharedPreferencesUtil(sharedPreferences: sharedPreferences);

        const expectedCount = counterValue;
        final actualCounter = sharedPreferencesUtil.getCount();
        expect(expectedCount, actualCounter);
      });
    });
  });
}
</code></pre>
<h2>Testing the setCounter() method</h2>
<ul>
<li><p><em>Test that the</em> <code>setCount()</code> <em>method stores the correct value in</em> <code>SharedPreferences</code><em>.</em></p>
<p>We first call the <code>SharedPreferences.setMockInitialValues()</code> and pass it <code>{}</code> (empty <code>Map</code> object) method to make sure nothing is stored in <code>SharedPreferences</code>. We, then, pass it into the <code>SharedPreferencesUtil</code> class.</p>
<p>We, then, can call the <code>SharedPreferences.getInt()</code> method, pass the <code>SharedPreferencesUtil.countKey</code> key to it to get the value in <code>SharedPreferences</code> compare it with the expected value in the <code>countValue</code> variable.</p>
</li>
</ul>
<pre><code class="language-dart">import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_unit_tests_flutter/shared_preferences_util.dart';
import 'package:test/test.dart';

main() {
  group(SharedPreferencesUtil, () {
    group('getCounter', () {
      test('returns 0 if no value is stored in SharedPreferences', () async {
        ...
      });

      test('returns the correct value stored in SharedPreferences', () async {
        ...
      });
    });

    group('setCounter', () {
      test('stores the correct count value in SharedPreferences', () async {
        SharedPreferences.setMockInitialValues({});
        final SharedPreferences sharedPreferences =
            await SharedPreferences.getInstance();

        final SharedPreferencesUtil sharedPreferencesUtil =
            SharedPreferencesUtil(sharedPreferences: sharedPreferences);
        const countValue = 42;

        sharedPreferencesUtil.setCount(countValue);
        const expectedCounter = countValue;
        final actualCounter =
            sharedPreferences.getInt(SharedPreferencesUtil.countKey);

        expect(expectedCounter, actualCounter);
      });
    });
  });
}
</code></pre>
<h2>Complete Test File</h2>
<p>The content of the entire test file is shown below:</p>
<pre><code class="language-dart">import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_unit_tests_flutter/shared_preferences_util.dart';
import 'package:test/test.dart';

main() {
  group(SharedPreferencesUtil, () {
    group('getCounter', () {
      test('returns 0 if no value is stored in SharedPreferences', () async {
        SharedPreferences.setMockInitialValues({});

        final SharedPreferences sharedPreferences =
            await SharedPreferences.getInstance();

        final SharedPreferencesUtil sharedPreferencesUtil =
            SharedPreferencesUtil(sharedPreferences: sharedPreferences);

        const expectedCounter = 0;
        final actualCounter = sharedPreferencesUtil.getCount();

        expect(expectedCounter, actualCounter);
      });

      test('returns the correct value stored in SharedPreferences', () async {
        const counterValue = 42;
        SharedPreferences.setMockInitialValues(
            {SharedPreferencesUtil.countKey: counterValue});
        final SharedPreferences sharedPreferences =
            await SharedPreferences.getInstance();

        final SharedPreferencesUtil sharedPreferencesUtil =
            SharedPreferencesUtil(sharedPreferences: sharedPreferences);

        const expectedCount = counterValue;
        final actualCounter = sharedPreferencesUtil.getCount();
        expect(expectedCount, actualCounter);
      });
    });

    group('setCounter', () {
      test('stores the correct count value in SharedPreferences', () async {
        SharedPreferences.setMockInitialValues({});
        final SharedPreferences sharedPreferences =
            await SharedPreferences.getInstance();

        final SharedPreferencesUtil sharedPreferencesUtil =
            SharedPreferencesUtil(sharedPreferences: sharedPreferences);
        const countValue = 42;

        sharedPreferencesUtil.setCount(countValue);
        const expectedCounter = countValue;
        final actualCounter =
            sharedPreferences.getInt(SharedPreferencesUtil.countKey);

        expect(expectedCounter, actualCounter);
      });
    });
  });
}
</code></pre>
<h1>Conclusion</h1>
<p>Mocking the <code>SharedPreferences</code> object in tests makes use of the <code>setMockInitialValues</code> method to initialize the state.</p>
<p>The complete code can be found on <a href="https://github.com/victoreronmosele/shared-preferences-unit-test-flutter">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Mocking and Testing The File System In Dart/Flutter Unit Tests]]></title><description><![CDATA[This article will describe how to mock and test the file system in Dart/Flutter for tests and in particular unit tests. This article assumes that the…]]></description><link>https://blog.victoreronmosele.com/mocking-filesystems-dart</link><guid isPermaLink="true">https://blog.victoreronmosele.com/mocking-filesystems-dart</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Testing]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[Dart]]></category><dc:creator><![CDATA[Victor Eronmosele]]></dc:creator><pubDate>Sat, 09 Oct 2021 19:47:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1633767608602/vq1yGMPhL.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article will describe how to mock and test the file system in Dart/Flutter for tests and in particular unit tests.</p>
<p>This article assumes that the reader is familiar with Flutter development and the Dart language.</p>
<p>The article is divided into:</p>
<ol>
<li><p><a href="#introduction">Introduction</a></p>
</li>
<li><p><a href="#dartio">Using the dart:io library</a></p>
</li>
<li><p><a href="#file">Using the file library</a></p>
</li>
<li><p><a href="#conclusion">Conclusion</a></p>
</li>
</ol>
<h2>1. Introduction</h2>
<p>We want to create a function <code>createHelloWorldFile</code> that creates a file <code>hello_world.dart</code> at a location <code>generated/hello_world.dart</code>.</p>
<p>We also want to unit test this function to ensure that the file is created at the specific location when the function runs.</p>
<p>We'll look at two different ways of doing this:</p>
<ul>
<li><p><a href="#dartio">Using the dart:io library</a></p>
</li>
<li><p><a href="#file">Using the file library</a></p>
</li>
</ul>
<h2>2. Using the dart:io library</h2>
<h3>Writing the Function</h3>
<p>This implementation is to make use of the <a href="https://api.dart.dev/dart-io/dart-io-library.html">dart:io</a> library and its <a href="https://api.dart.dev/stable/dart-io/File-class.html">File</a> object to create the file.</p>
<p>We first create the <code>File</code> object with the desired location passed as a parameter and call <code>.createSync</code> to create the file.</p>
<p><code>recursive:true</code> is needed to ensure that any non-existing path is created first before creating the file.</p>
<p>Here is the code for the function:</p>
<pre><code class="language-dart">import 'dart:io';

void createHelloWorldFile() {
  final file = File('generated/hello_world.dart');
  file.createSync(recursive: true);
}
</code></pre>
<h3>Calling the Function</h3>
<p>We can call the function like this:</p>
<pre><code class="language-dart">import 'dart:io';

void main(List&lt;String&gt; arguments) {
  createHelloWorldFile();
}
</code></pre>
<h3>Testing the Function</h3>
<p>The first step is to add the test library to <code>dev_dependencies</code> in the <code>pubspec.yaml</code> file like this:</p>
<pre><code class="language-yaml">dev_dependencies:
  test:
</code></pre>
<p>The next step is to write the test for the function like this:</p>
<pre><code class="language-dart">import 'dart:io';
import 'package:test/test.dart';

void main() {
  test('createHelloWorldFile creates a file at generated/hello_world.dart', () {
    createHelloWorldFile();
    final file = File('generated/hello_world.dart');
    expect(file.existsSync(), true);
  });
}
</code></pre>
<p>The test code above uses the <a href="https://api.dart.dev/stable/2.14.3/dart-io/FileSystemEntity/existsSync.html">.existsSync</a> property on the created <code>File</code> object to confirm if it does exist.</p>
<p>The test passes when it is run.</p>
<h3>The Problem with the Test</h3>
<p>Running this test passes but the problem with this test is that it actually creates the <code>generated/hello_world.dart</code> file.</p>
<p>This generated file is not needed for the actual test so it would be better to use a mock file system so we can write/run as many tests as we want without worrying about side effects.</p>
<h2>3. Using the file library</h2>
<h3>Writing the Function</h3>
<p>To solve the problem with the extra file generated, we will use the <a href="https://pub.dev/packages/file">file</a> library which gives the ability to create custom file systems and in-memory file systems for easy unit testing of code that works with file systems.</p>
<p>The first step is to add the <code>file</code> library to <code>dependecies</code> in our <code>pubspec.yaml</code> file like this:</p>
<pre><code class="language-yaml">dependencies:
  file:
</code></pre>
<p>The next step is to update our <code>createHelloWorldFile</code> function to this:</p>
<pre><code class="language-dart">import 'package:test/test.dart';
import 'package:file/file.dart';

void createHelloWorldFile(FileSystem fileSystem) {
  final file = fileSystem.file('generated/hello_world.dart');
  file.createSync(recursive: true);
}
</code></pre>
<p>In the code above, we inject the fileSystem into the function <code>createHelloWorldFile</code> and use that to create the file.</p>
<h3>Calling the Function</h3>
<p>To call the function, we pass a <a href="https://pub.dev/documentation/file/latest/local/LocalFileSystem-class.html">LocalFileSystem</a> object into the <code>createHelloWorldFile</code> function.</p>
<blockquote>
<p>LocalFileSystem class</p>
</blockquote>
<blockquote>
<p>A wrapper implementation around dart:io's implementation.</p>
</blockquote>
<blockquote>
<p>Since this implementation of the FileSystem interface delegates to dart:io, [it] is not suitable for use in the browser.</p>
</blockquote>
<pre><code class="language-dart">import 'package:file/local.dart';

void main(List&lt;String&gt; arguments) {
  final localFileSystem = LocalFileSystem();
  createHelloWorldFile(localFileSystem);
}
</code></pre>
<h3>Testing the Function</h3>
<p>In order to test the function, we can pass a <a href="https://pub.dev/documentation/file/latest/memory/MemoryFileSystem-class.html">MemoryFileSystem</a> object into the <code>createHelloWorldFile</code>.</p>
<blockquote>
<p>MemoryFileSystem class</p>
</blockquote>
<blockquote>
<p>An implementation of FileSystem that exists entirely in memory with an internal representation loosely based on the Filesystem Hierarchy Standard.</p>
</blockquote>
<blockquote>
<p>MemoryFileSystem is suitable for mocking and tests, as well as for caching or staging before writing or reading to a live system.</p>
</blockquote>
<pre><code class="language-dart">import 'package:file/memory.dart';
import 'package:test/test.dart';

void main() {
  test('createHelloWorldFile creates a file at generated/hello_world.dart', () {
    final memoryFileSystem = MemoryFileSystem();
    createHelloWorldFile(memoryFileSystem);

    final file = memoryFileSystem.file('generated/hello_world.dart');

    expect(file.existsSync(), true);
  });
}
</code></pre>
<p>Running this test passes and it does not create any extra files.</p>
<h2>4. Conclusion</h2>
<p>The <a href="https://api.dart.dev/stable/dart-io/File-class.html">file</a> library provides an easy way to test operations involving files with the use of the <code>MemoryFileSystem</code> which is an in-memory file system that does not write to the actual file system.</p>
<p>The complete project can be found on <a href="https://github.com/victoreronmosele/file-system-test-dart">Github</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Mocking callbacks in Dart/Flutter unit tests]]></title><description><![CDATA[This article is a guide on how to mock callback functions and verify that the callback functions are called in Dart/Flutter unit tests. The article is…]]></description><link>https://blog.victoreronmosele.com/mocking-callbacks-dart</link><guid isPermaLink="true">https://blog.victoreronmosele.com/mocking-callbacks-dart</guid><category><![CDATA[Testing]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Dart]]></category><dc:creator><![CDATA[Victor Eronmosele]]></dc:creator><pubDate>Fri, 24 Sep 2021 14:52:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632495208967/e15Bt_6n_.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is a guide on how to mock callback functions and verify that the callback functions are called in Dart/Flutter unit tests.</p>
<p>The article is divided into:</p>
<ol>
<li><p><a href="#introduction">Introduction</a></p>
</li>
<li><p><a href="#mocking">Mocking The Callback</a></p>
</li>
<li><p><a href="#testing">Testing The Callback</a></p>
</li>
</ol>
<h2>1. Introduction</h2>
<p>Let's say we have a function <code>readDate</code> with the definition below:</p>
<pre><code class="language-dart">void readData(void Function() onDataReadComplete) {
    print('Reading data');
    onDataReadComplete();
}
</code></pre>
<p>The function takes a callback <code>onDataReadComplete</code> as a lone <a href="https://dart.dev/guides/language/language-tour#parameters">positional parameter</a> and it calls <code>onDataReadComplete</code> after it prints ('Reading data').</p>
<p>Our task here is to write a unit test to confirm that <code>onDataReadComplete</code> is run whenever <code>readData</code> runs.</p>
<p>In order to do this we need to mock <code>onDataReadComplete</code> and confirm that it is actually called.</p>
<h2>2. Mocking The Callback</h2>
<p>In other to mock the callback, we will use the mock library <a href="https://pub.dev/packages/mockito">mockito</a>.</p>
<p>The first step is to add the <code>mockito</code> dependecy to our project by including it in the <code>pubspec.yaml</code> file. We will also add the <a href="https://pub.dev/packages/test">test</a> library to the <code>pubspec.yaml</code> file.</p>
<pre><code class="language-yaml">dev_dependencies:
  mockito:
  test:
</code></pre>
<p>Mockito has two ways to generate mock objects:</p>
<ol>
<li><p><a href="https://github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md#code-generation">Code Generation</a></p>
</li>
<li><p><a href="https://github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md#manual-mock-implementaion">Manual Mock Implementation</a></p>
</li>
</ol>
<p>For this article, we will use the manual mock implementation for simplicity.</p>
<p>A class can be mocked manually by creating a class that extends Mock and implements the class to be mocked.</p>
<p>Below is a sample from the documentation:</p>
<pre><code class="language-dart">class MockHttpServer extends Mock implements HttpServer {}
</code></pre>
<p>This means we need a class to represent our function so our mock class can implement it.</p>
<p>We will make use of Dart's <a href="https://dart.dev/guides/language/language-tour#callable-classes">Callable Classes</a>.</p>
<blockquote>
<p>To allow an instance of your Dart class to be called like a function, implement the call() method.</p>
<p>- <a href="https://dart.dev/guides/language/language-tour#callable-classes">Callable Classes</a></p>
</blockquote>
<p>This means we can represent our <code>void Function() onDataReadComplete</code> function as this below:</p>
<pre><code class="language-dart">abstract class OnDataReadComplete {
    void call();
}
</code></pre>
<p>The class is an <code>abstract</code> class since we won't be providing an implementation of the <code>call</code> method .</p>
<p>The <code>call</code> method must have the same definition as the function to be mocked. This is why it is a <code>void</code> method.</p>
<p>Now, we can create our mock class like this below:</p>
<pre><code class="language-dart">class MockOnDataReadComplete extends Mock implements OnDataReadComplete {}
</code></pre>
<p>We can now, use <code>MockOnDataReadComplete</code> in our test.</p>
<h2>3. Testing The Callback</h2>
<p>We will follow the following steps in testing the callback function:</p>
<ol>
<li><p>Create the mock object <code>mockOnDataReadComplete</code> using <code>MockOnDataReadComplete</code>.</p>
</li>
<li><p>Run the <code>readData</code> function with <code>mockOnDataReadComplete</code> passed as a parameter.</p>
</li>
<li><p>Use the <code>verify</code> function to confirm that <code>mockOnDataReadComplete()</code> is called once. <em>Note that you need to call the function like this</em> <code>mockOnDataReadComplete()</code> <em>and not just pass the variable</em> <code>mockOnDataReadComplete</code> <em>to the verify function</em></p>
</li>
</ol>
<pre><code class="language-dart">test('onDataReadComplete gets called whenever readData runs', () {
    //Creates the mock object
    final mockOnDataReadComplete = MockOnDataReadComplete();

    //Runs the function
    readData(mockOnDataReadComplete);

    //Confirm that the mock object is called
    verify(mockOnDataReadComplete()).called(1);
  });
</code></pre>
<p>Here is the full test file:</p>
<pre><code class="language-dart">import 'package:mockito/mockito.dart';
import 'package:test/test.dart';

void readData(void Function() onDataReadComplete) {
  print('Reading data');
  onDataReadComplete();
}

abstract class OnDataReadComplete {
  void call();
}

class MockOnDataReadComplete extends Mock implements OnDataReadComplete {}

void main() {
  test('onDataReadComplete gets called whenever readData runs', () {
    //Creates the mock object
    final mockOnDataReadComplete = MockOnDataReadComplete();

    //Runs the function
    readData(mockOnDataReadComplete);

    //Confirm that the mock object is called
    verify(mockOnDataReadComplete()).called(1);
  });
}
</code></pre>
<p>And now we run our tests and it passes!</p>
<p>The complete project can be found on <a href="https://github.com/victoreronmosele/callback-test-dart">Github</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Rebuilding The Flutter Counter App In Jetpack Compose]]></title><description><![CDATA[A demonstration showing how to build a simple counter app using Jetpack Compose.]]></description><link>https://blog.victoreronmosele.com/flutter-counter-in-compose</link><guid isPermaLink="true">https://blog.victoreronmosele.com/flutter-counter-in-compose</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Flutter]]></category><category><![CDATA[Android]]></category><dc:creator><![CDATA[Victor Eronmosele]]></dc:creator><pubDate>Fri, 06 Aug 2021 20:09:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1628280317913/PKjye24Pq.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article will show how to rebuild the default <a href="https://flutter.dev/">Flutter</a> counter app using <a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a>.</p>
<p>The article is divided into two sections:</p>
<ol>
<li><p><a href="#ui">UI</a>, where the app's user interface will be built.</p>
</li>
<li><p><a href="#state">State</a>, where the state of the app's counter will be implemented.</p>
</li>
</ol>
<p>Below is a screenshot of the default Flutter counter app:</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1628273185586/9AM_bWM-k.jpeg" alt="162827266517692828 (3).jpeg" />

<p>This is what we'll rebuild with Jetpack Compose.</p>
<p>The first step is to download a <a href="https://developer.android.com/studio">Jetpack Compose supported Android Studio</a> version (at this time of writing, that is the Arctic Fox version).</p>
<p>The next step is to create an empty compose activity by clicking on File &gt; New Project and selecting <code>Empty Compose Activity</code> from the templates shown.</p>
<p>Click on <code>Next</code>.</p>
<p>Then we enter our application name. For this article, we'll use "ComposeCounterApp".</p>
<p>Click on <code>Finish</code> and it should open the <code>ComposeCounterApp</code> project.</p>
<h2>1. UI</h2>
<p>Open the <code>MainActivity.kt</code> file. It should contain the default Compose Activity code.</p>
<p>We'll remove the code and update the content of <code>MainActivity.kt</code> to this below:</p>
<pre><code class="language-kotlin">package com.example.composecounterapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import com.example.composecounterapp.ui.theme.ComposeCounterAppTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeCounterAppTheme {
                ComposeCounter()
            }
        }
    }
}

@Composable
fun ComposeCounter() {
    Scaffold(
        content = {}
    )
}
</code></pre>
<p>On running the project on a device, an empty screen is displayed. This is because <code>ComposeCounter</code> only contains a <a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#Scaffold">Scaffold</a> composable with empty content.</p>
<p>Next, we'll add the code for the app bar. We'll use the <a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#TopAppBar">TopAppBar</a> composable and specify the title, the background colour, and the content colour.</p>
<p>Update the <code>ComposeCounter</code> function to this.</p>
<pre><code class="language-kotlin">@Composable
fun ComposeCounter() {
    val primaryColor = Color(0xFF2196F3)

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = "Compose Home Demo Page") },
                backgroundColor = primaryColor,
                contentColor = Color.White
            )
        },
        content = {}
    )
}
</code></pre>
<p>This will show the following screen:</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1628272825854/iNS_NCNHS.jpeg" alt="162827266517692828.jpeg" />

<p>Next, we'll add the content of the screen. And for this, we'll pass a Column with two Texts to the Scaffold as <code>content</code>. The column items will be aligned in the center and we'll pass <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier">modifiers</a> to ensure the Column fills the screen horizontally and vertically.</p>
<pre><code class="language-kotlin">@Composable
fun ComposeCounter() {
    val primaryColor = Color(0xFF2196F3)

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = "Compose Home Demo Page") },
                backgroundColor = primaryColor,
                contentColor = Color.White
            )
        },
        content = {
            Column(
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier
                    .fillMaxHeight()
                    .fillMaxWidth()
            ) {
                Text(
                    text = "You have pushed this button this many times",
                )
                Text(
                    text = "0",
                    style = MaterialTheme.typography.h4,
                )
            }
        },
    )
}
</code></pre>
<p>And now we'll have this showing on our device.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1628272968634/ZF1NNk3dE.jpeg" alt="162827266517692828 (1).jpeg" />

<p>The last thing to add for the UI is the floating action button, which we can specify on the Scaffold by passing a <a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#FloatingActionButton">FloatingActionButton</a> composable to the Scaffold as <code>floatingActionButton</code>.</p>
<p>We do that by updating the <code>ComposeCounter</code> composable to the code below:</p>
<pre><code class="language-kotlin">@Composable
fun ComposeCounter() {
    val primaryColor = Color(0xFF2196F3)

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = "Compose Home Demo Page") },
                backgroundColor = primaryColor,
                contentColor = Color.White
            )
        },
        content = {
            Column(
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier
                    .fillMaxHeight()
                    .fillMaxWidth()
            ) {
                Text(
                    text = "You have pushed this button this many times",
                )
                Text(
                    text = "0",
                    style = MaterialTheme.typography.h4,
                )
            }
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {},
                backgroundColor = primaryColor,
                contentColor = Color.White
            ) {
                Icon(Icons.Filled.Add, contentDescription = "Add button")
            }
        },
    )
}
</code></pre>
<p>And now, we'll have our complete UI! 🎉</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1628273060642/L88MXLIwy.jpeg" alt="162827266517692828 (2).jpeg" />

<h2>2. State</h2>
<p>Currently, the app displays "0" as the counter state and we need to make sure that clicking the floating action button increments that state.</p>
<p>We need a variable to hold the state of the counter.</p>
<p>From <a href="https://developer.android.com/jetpack/compose/state">State and Jetpack Compose</a>,</p>
<blockquote>
<p>There are three ways to declare a MutableState object in a composable:</p>
</blockquote>
<blockquote>
<ul>
<li><p>val mutableState = remember { mutableStateOf(default) }</p>
</li>
<li><p>var value by remember { mutableStateOf(default) }</p>
</li>
<li><p>val (value, setValue) = remember { mutableStateOf(default) }</p>
</li>
</ul>
</blockquote>
<p>We'll be using the second one.</p>
<p>At the top of the <code>ComposeCounter</code> composable, we'll add a variable <code>counter</code> to hold the state of the counter and set its default value to zero.</p>
<p>We'll also use this <code>counter</code> variable in the Text composable instead of "0".</p>
<p>And now the <code>ComposeCounter</code> will have the following code:</p>
<pre><code class="language-kotlin">@Composable
fun ComposeCounter() {
    val primaryColor = Color(0xFF2196F3)
    var counter: Int by remember { mutableStateOf(0) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = "Compose Home Demo Page") },
                backgroundColor = primaryColor,
                contentColor = Color.White
            )
        },
        content = {
            Column(
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier
                    .fillMaxHeight()
                    .fillMaxWidth()
            ) {
                Text(
                    text = "You have pushed this button this many times",
                )
                Text(
                    text = counter.toString(),
                    style = MaterialTheme.typography.h4,
                )
            }
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {
                },
                backgroundColor = primaryColor,
                contentColor = Color.White
            ) {
                Icon(Icons.Filled.Add, contentDescription = "Add button")
            }
        },
    )
}
</code></pre>
<p>There will be no visible change on the screen for now.</p>
<p>The next thing to do is to increment the counter when the floating action button is clicked.</p>
<p>We can do that in the <code>onClick</code> callback of the <code>FloatingActionButton</code>.</p>
<p>The code will be updated to this:</p>
<pre><code class="language-kotlin">@Composable
fun ComposeCounter() {
    val primaryColor = Color(0xFF2196F3)
    var counter: Int by remember { mutableStateOf(0) }


    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = "Compose Home Demo Page") },
                backgroundColor = primaryColor,
                contentColor = Color.White
            )
        },
        content = {
            Column(
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier
                    .fillMaxHeight()
                    .fillMaxWidth()
            ) {
                Text(
                    text = "You have pushed this button this many times",
                )
                Text(
                    text = counter.toString(),
                    style = MaterialTheme.typography.h4,
                )
            }
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {
                    counter += 1
                },
                backgroundColor = primaryColor,
                contentColor = Color.White
            ) {
                Icon(Icons.Filled.Add, contentDescription = "Add button")
            }
        },
    )
}
</code></pre>
<p>Now the app increments the counter when the floating action button is tapped as seen in the gif below:</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1628273301925/_R-MgXVVO.gif" alt="162827266517692828.gif" />

<p>And now the app is complete.</p>
<p>The complete code for the <code>MainActivity.kt</code> is this below:</p>
<pre><code class="language-kotlin">package com.example.composecounterapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.example.composecounterapp.ui.theme.ComposeCounterAppTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeCounterAppTheme {
                ComposeCounter()
            }
        }
    }
}

@Composable
fun ComposeCounter() {
    val primaryColor = Color(0xFF2196F3)
    var counter: Int by remember { mutableStateOf(0) }


    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = "Compose Home Demo Page") },
                backgroundColor = primaryColor,
                contentColor = Color.White
            )
        },
        content = {
            Column(
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier
                    .fillMaxHeight()
                    .fillMaxWidth()
            ) {
                Text(
                    text = "You have pushed this button this many times",
                )
                Text(
                    text = counter.toString(),
                    style = MaterialTheme.typography.h4,
                )
            }
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {
                    counter += 1
                },
                backgroundColor = primaryColor,
                contentColor = Color.White
            ) {
                Icon(Icons.Filled.Add, contentDescription = "Add button")
            }
        },
    )
}
</code></pre>
<p>The complete project can be found on <a href="https://github.com/victoreronmosele/compose-counter-app">Github</a>.</p>
]]></content:encoded></item></channel></rss>