嘲笑一个集合的方法

发布于 2025-01-26 22:30:54 字数 1028 浏览 1 评论 0原文

我有调用MongoDB集合以获取列表的方法。我想嘲笑列表的结果,但我在其中得到了NPE。

public String convertId(String Id, int counter) {
    String id2 = "test";
    List<Object> objectList = new ArrayList<>();
    collection.find(eq(id,id2)).into(objectList);
    Object obj = objectList.get(0);
    return obj.getId();
}

我在Collection.find方法上获得了零指针。撰写测试案例是:

@Test
public void convertIdTest() {
    List<Object> objectList = new ArrayList<>();
    Document doc1 = new Document();
    Mockito.when(collection.find(Mockito.any(BasicDBObject.class))).thenReturn(iterable);
    Mockito.when(iterable.iterator()).thenReturn(cursor);
    Mockito.when(cursor.hasNext()).thenReturn(true).thenReturn(false);
    Mockito.when(cursor.next).thenReturn(doc1);
    assertNotNull(request.converId("1233",1);
}

====================================

FindIterable<Object> iterable = mock(FindIterable.class)
MongoCursor cursor = mock(MongoCursor.class)

I have method that is calling mongodb collection to get a list. I want to mock the outcome of the list but i am getting NPE on it.

public String convertId(String Id, int counter) {
    String id2 = "test";
    List<Object> objectList = new ArrayList<>();
    collection.find(eq(id,id2)).into(objectList);
    Object obj = objectList.get(0);
    return obj.getId();
}

I am getting null pointer on collection.find method. The test case is wrote is :

@Test
public void convertIdTest() {
    List<Object> objectList = new ArrayList<>();
    Document doc1 = new Document();
    Mockito.when(collection.find(Mockito.any(BasicDBObject.class))).thenReturn(iterable);
    Mockito.when(iterable.iterator()).thenReturn(cursor);
    Mockito.when(cursor.hasNext()).thenReturn(true).thenReturn(false);
    Mockito.when(cursor.next).thenReturn(doc1);
    assertNotNull(request.converId("1233",1);
}

≈========≈========================

iterable is of type:

FindIterable<Object> iterable = mock(FindIterable.class)
MongoCursor cursor = mock(MongoCursor.class)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文