Run Java tests against the Firestore emulator

Run Java tests against the Firestore emulator

It's not widely documented how to do this, right? You have a test suite that you want to run against Firestore emulator, which should get started and stopped automatically while the tests are running. In this case, we will be using Java.

Connecting to local Firestore is quite straightforward, though poorly documented:

var options = FirestoreOptions.getDefaultInstance()
var firestoreUrl = System.getenv("FIRESTORE_URL");
if (!Strings.isNullOrEmpty(firestoreUrl) {
} else {
Firestore instance =;

This will connect Firestore to your local environment if you pass an environment variable named FIRESTORE_URL, and if not defined it will try to connect to the real service using the default Service Account for Compute Engine (if the code is running on a CI/CD environment, or just fail noisily if it's your local laptop). You can configure gradle to launch the emulator before your tests.

bin/start-firestore-emulator will launch the emulator on port 9000:

# Launch firestore emulator on port 9000

waitport() {
  while ! nc -z localhost $1; do 
    sleep 1 

PID=$(lsof -t -i :9000 -s tcp:LISTEN)
if [ -z "$PID" ]; then
  echo "Starting mock Firestore server on port 9000"
  nohup gcloud beta emulators firestore start \
    --host-port= \
    > /tmp/mock-firestore-logs &
  waitport 9000
  echo "There is an instance of Firestore already running on port 9000"

bin/stop-firestore-emulator will kill whatever is running on port 9000, so better it be your emulator:

# Stop mock firestore 

if [ ! -z "$PID" ]; then
  echo "Stopping mock Firestore server"
  kill "$PID"

These two scripts will start and stop Firestore locally on port 9000. Now we need to trigger them before and after launching our tests in build.gradle:

task startMockFirestore {
  doFirst {
    ext.process = new ProcessBuilder()

task stopMockFirestore(type: Exec) {
  executable "bin/stop-firestore-emulator"

As bonus points, IntelliJ will automatically use these tasks when launching individual tests, which is nice. One last note: remember that the Firestore emulator will not persist anything between executions – once you kill the server, you lose the data.

Hope this is useful!