Fake the response of the Firebase Realtime Database APIs in XCTest

Toru Furuya
2 min readOct 27, 2018

--

I’m using the Firebase Realtime Database at work and found this article (written in Japanese) when I was searching about Mocking for the unit testing with Firebase Realtime Database.

It is also written that more than Mocking the Realtime Database and that makes it so useful. This time, I tried to consider an easier way to mock the response of the Realtime Database in XCTest. I hope it’ll be helpful for people who don’t want to do complicated stuff.

App Code

This app code does like as following stuff:

  • Being passed the instance of DatabaseRefenrece to the constructor.
  • Get the data for the path of “sample” once using observeSingleEvent API.
  • Do some operation to the snapshot in the response and pass the result to the completion block.

Test Code

All the unit test code for the app looks like this. Let’s see one by one.

Test Case

Let’s begin with the test case. Make the target class’s instance at the first line. At that time, pass the MockDatabaseReference which is a mock object of DatabaseReference class as a constructor argument. I’ll explain about that mock class later. Besides, use the XCTestExpectation because getting the data from Realtime Database should be asynchronous operation.

Override DatabaseReference

This is the mock object of DatabaseReference class that was mentioned in a bit before. App code, this time, uses observeSingleEvent API so override that function, and child function as well.

The reason why override the child function is that, if app code uses child API for requesting the specific path data, that API returns another new instance of DatabaseReference, and then we can’t mock the response. Hence, this time, override the child API and return the mock object itself so that any path can be requested by the app code while realizing mocking.

If you want to change the response data depends on the requested path, you may be able to do that by overriding child API and returning the different mock object of DatabaseReference for each path as follows:

Override DataSnapshot

Last, override the DataSnapshot class which is actual response data. The value property of the DataSnapshot is originally read-only property, so we can’t make it as we like. Thus, override that and return the data we want to use as test data.

By using this MockSnapshot object in the MockDatabaseReference class’s observeSingleEvent, we finally can make the Firebase Realtime Database API returns the data as we want.

--

--