0

So I am attempting to use the Cloud Firestore offline cache ONLY as an API for my instrumentation tests, to avoid having to read and write from the server database during my integration tests.

First, in my test setup method, I call this method

protected fun setFirestoreToOfflineMode() {
    Tasks.await(FirebaseFirestore.getInstance().disableNetwork())
}

Then, at the beginning of each relevant test, I use

fun givenHasTrips(vararg trips: Trip) {
    GlobalScope.launch(Dispatchers.Default) {
        trips.forEach {
            firestoreTripApi.put(it)
        }
    }
}

In that put method, I have the following code:

try {
    Tasks.await(tripCollection().document(tripData.id).set(tripData)),
                    firestoreApiTimeoutSeconds, TimeUnit.SECONDS)
    Either.Right(Unit)
} catch (e: Throwable) {
    Either.Left(Failure.ServerError)
}

I am calling the set() method and am waiting for a successful result in order to be able to return that the operation was a success, to update my UI afterward.

What happens is the cache DB is written correctly BUT the "set()" function times out because the database is in offline mode. I have read that Firestore only confirms a success if the Server DB was correctly written. If that is the case, I do not know if it is possible to have this call not time-out when operating strictly in offline-cache mode.

Is there a solution to have Firestore act as if the local cache database was the source of truth and return successes if placed in offline mode, just for tests?

Sean Blahovici
  • 5,350
  • 4
  • 28
  • 38

1 Answers1

2

The Task returned by the methods that modify the database (set, update, delete) only issues a callback when the data is fully committed to the cloud. There is no way to change this behavior.

What you can do instead is set up a listener to the document(s) that are expected to change, and wait for the listener to trigger. The listener will trigger even while offline.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441