gpt4 book ai didi

java - Mockito FindIterable<文档>

转载 作者:搜寻专家 更新时间:2023-11-01 01:49:08 26 4
gpt4 key购买 nike

我正在尝试为以下方法编写 JUnit 测试用例,我正在使用 Mockito 框架。

方法:

public EmplInfo getMetaData(String objectId) {

objectId = new StringBuffer(objectId).reverse().toString();
try{
BasicDBObject whereClauseCondition = getMetaDataWhereClause(objectId);
EmplInfo emplinfo= new EmplInfo ();
emplinfo.set_id(objectId);
FindIterable<Document> cursorPersonDoc = personDocCollection.find(whereClauseCondition);
for (Document doc : cursorPersonDoc) {
emplinfo.setEmplFirstName(doc.getString("firstname"));
emplinfo.setEmplLastName(doc.getString("lastname"));
break;
}
return emplinfo;
}catch(Exception e){
e.printstacktrace();
}

联合:

@Test
public void testGetMetaData() throws Exception {
String docObjectId = "f2da8044b29f2e0a35c0a2b5";
BasicDBObject dbObj = personDocumentRepo.getMetaDataWhereClause(docObjectId);
FindIterable<Document> findIterable = null;
Mockito.when(collection.find(dbObj)).thenReturn(findIterable);
personDocumentRepo.getMetaData(docObjectId);
}

我在“personDocumentRepo.getMetaData(docObjectId)”中得到空点预期,因为我“返回”为 NULL 的 findIterable。不确定如何将虚拟/测试值分配给 findIterable。

请指教。

谢谢!巴拉蒂

最佳答案

正如您正确指出的那样,您将获得 NPE,因为 FindIterable 为 null。你需要模拟它。
模拟它并不是那么简单,因为它使用 MongoCursor(这又扩展了 Iterator),您需要模拟内部使用的某些方法。

在遍历Iter的某些方法时

我相信你必须做这样的事情。

FindIterable iterable = mock(FindIterable.class);
MongoCursor cursor = mock(MongoCursor.class);

Document doc1= //create dummy document;
Document doc2= //create dummy document;

when(collection.find(dbObj)).thenReturn(iterable);

when(iterable.iterator()).thenReturn(cursor);
when(cursor.hasNext())
.thenReturn(true)
.thenReturn(true)// do this as many times as you want your loop to traverse
.thenReturn(false); // Make sure you return false at the end.
when(cursor.next())
.thenReturn(doc1)
.thenReturn(doc2);

这不是一个完整的解决方案。您需要根据您的类(class)进行调整。

关于java - Mockito FindIterable<文档>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50987954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com