Pritam Sangani
Pritam Sangani

Reputation: 301

Cloud Firestore Unit Testing Java

I am creating a REST API in Spring Boot and I am stuck with unit testing my service, which makes calls to my firestore database. I am trying to mock my Firestore database so I don't add unnecessary data to my firestore database as part of my tests. However, when I try to stub responses on the mocked Firestore object, I am getting a Null Pointer Exception. I am using JUnit 5 and mocking the Firestore class by

@Mock
private Firestore db;

@InjectMocks
private ProductsService productsService;

In my test, I am stubbing a response from a method of the Firestore object by

// Getting a null pointer exception here
when(db.collection("products").add(productToCreate).get()).thenReturn(any(DocumentReference.class));

Upvotes: 4

Views: 3118

Answers (2)

Konzern
Konzern

Reputation: 128

@Mock
private Firestore db;
@Mock
private CollectionReference colRef;
@Mock
private DocumentReference docRef;
@sneakthrows
public void test(){
when(db.collection(any(String.class))).thenReturn(colRef);
when(colRef.document(any(String.class))).thenReturn(docRef);
}

You need to perform deep stubbing mockito, reference in my javabelazy blog

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317750

You will have to mock not just Firestore, but also every object returned in each chain of method calls that come from it. Mocks are not "deep" and don't know how to generate more mock objects for the methods on that mock. You have to tell it what to return for each method call individually.

Upvotes: 4

Related Questions