【发布时间】:2020-03-01 23:08:09
【问题描述】:
我正在 Spring Boot 中创建一个 REST API,但我一直在对我的服务进行单元测试,这会调用我的 firestore 数据库。我正在尝试模拟我的 Firestore 数据库,因此我不会在我的测试中将不必要的数据添加到我的 Firestore 数据库中。但是,当我尝试在模拟的 Firestore 对象上存根响应时,我得到一个空指针异常。我正在使用 JUnit 5 并通过
模拟 Firestore 类@Mock
private Firestore db;
@InjectMocks
private ProductsService productsService;
在我的测试中,我将 Firestore 对象的方法的响应存根
// Getting a null pointer exception here
when(db.collection("products").add(productToCreate).get()).thenReturn(any(DocumentReference.class));
【问题讨论】:
-
您不仅要模拟
Firestore,还要模拟来自它的每个方法调用链中返回的每个对象。模拟不是“深”的,也不知道如何为该模拟上的方法生成更多模拟对象。您必须单独告诉它为每个方法调用返回什么。 -
这行得通。谢谢@DougStevenson。如果您想创建一个答案,我会将其标记为已接受的答案。
标签: java spring-boot google-cloud-firestore mockito junit5