【问题标题】:Cloud Firestore Unit Testing JavaCloud Firestore 单元测试 Java
【发布时间】: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


【解决方案1】:

您不仅要模拟Firestore,还要模拟来自它的每个方法调用链中返回的每个对象。模拟不是“深”的,也不知道如何为该模拟上的方法生成更多模拟对象。您必须告诉它为每个方法调用单独返回什么。

【讨论】:

  • 你有什么例子吗?
【解决方案2】:
@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);
}

你需要执行深度存根 mockito,参考我的 javabelazy 博客

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 2021-10-15
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多