我正在尝试为下面的方法编写一个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();
}
Junit的:
@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)”中得到零点预测,因为我“返回”了findIterable,它是NULL.不确定如何将伪/测试值分配给findIterable.
请指教.
谢谢!
Bharathi
解决方法:
正如您正确指出的那样,您正在获取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);
这不是一个完整的解决方案.你需要适应你的课程.