Cloud Firestore 单元测试 Java
Cloud Firestore Unit Testing Java
我正在 Spring 引导中创建一个 REST API,我一直在对我的服务进行单元测试,这会调用我的 firestore 数据库。我正在尝试模拟我的 Firestore 数据库,这样我就不会在我的测试中向我的 firestore 数据库添加不必要的数据。但是,当我尝试对模拟的 Firestore 对象存根响应时,我收到空指针异常。我正在使用 JUnit 5 并通过
模拟 Firestore class
@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
,还要模拟每个对象 return 来自它的每个方法调用链中的每个对象。模拟不是 "deep" 并且不知道如何为该模拟上的方法生成更多模拟对象。对于每个方法调用,您必须单独告诉它 return 什么。
@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);
}
你需要执行 deep stubbing mockito,参考我的 javabelazy 博客
我正在 Spring 引导中创建一个 REST API,我一直在对我的服务进行单元测试,这会调用我的 firestore 数据库。我正在尝试模拟我的 Firestore 数据库,这样我就不会在我的测试中向我的 firestore 数据库添加不必要的数据。但是,当我尝试对模拟的 Firestore 对象存根响应时,我收到空指针异常。我正在使用 JUnit 5 并通过
模拟 Firestore class@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
,还要模拟每个对象 return 来自它的每个方法调用链中的每个对象。模拟不是 "deep" 并且不知道如何为该模拟上的方法生成更多模拟对象。对于每个方法调用,您必须单独告诉它 return 什么。
@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);
}
你需要执行 deep stubbing mockito,参考我的 javabelazy 博客