2

I have a repository which reads and writes to Firestore, and some tests to make sure data is sent and comes back in the correct way.

In order to test this I added a protected function which returns the root collection I'm working with, i.e. protected open fun users() = firestore.collection("users"), which is overridden in a test class override fun users() = firestore.collection("test-users"), so all the logic remains the same but I'm not testing on any production data.

This is a potentially flimsy solution, as if firestore.collection("users") is called anywhere in the parent class instead of users() the test collection will not be used.

Is this the best way of handling this, or should a different approach be employed?

1 Answer 1

10

You should use a different approach. The commonly advised approaches are

  1. Use DI to inject the firestore object into your repository class instance. This way, your test framework can just inject a mock firestore object that doesn't connect to google but gives prepared answers instead.

    The great benefit here is that your tests don't become temporally dependent on each other via the contents of the database.

  2. Make the connection information that is used to connect to Firestore configurable. This allows 2 things that are a good practice

    1. You can keep the production credentials out of your source code repository. The fewer people that have knowledge of these credentials, the easier you can make sure they don't leak.
    2. You can configure your testing environment to connect to a different Firestore instance, by using a different account. That testing instance can have the same structure as your production version (so you don't have to do tricks in the code), but would have different contents.

I would recommend to actually use both approaches (and the can be used at the same time).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.