我为集合指定了空值,即MongoCollection<Document> collection = null;
@Override
public List<Document> viewUserData(String conditionVar, String conditionVal) {
List<Document> list = new ArrayList<>();
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put(conditionVar, conditionVal);
FindIterable<Document> userDocuments = collection.find(whereQuery);
for (Document doc : userDocuments) {
list.add(doc);
}
return list;
}
@Test
public void ViewUserData(){
List<Document> list = new ArrayList<>();
Document doc1=new Document();
doc1.append("1","bharathi");
list.add(doc1);
FindIterable<Document> documents = collection.find(doc1);
Mockito.when(collection.find(Mockito.any(BasicDBObject.class)))
.thenReturn(documents); mdmdaoimpl.viewUserData("1","bharathi");
verify(collection,times(1)).find(doc1);
}
测试代码:
@Test public void ViewUserData() {
List<Document> list = new ArrayList<>();
Document doc1=new Document();
doc1.append("1","bharathi");
list.add(doc1);
FindIterable<Document> documents = collection.find(doc1);
Mockito.when(collection.find(Mockito.any(BasicDBObject.class))).thenReturn(documents);
mdmdaoimpl.viewUserData("1","bharathi");
verify(collection,times(1)).find(doc1);
}
答案 0 :(得分:0)
@Test
public void ViewUserData(){
FindIterable iterable = mock(FindIterable.class);
MongoCursor cursor = mock(MongoCursor.class);
Document doc1=new Document("1","bharathi");
Document doc2=new Document("2","madhavi");
when(iterable.iterator()).thenReturn(cursor);
when(cursor.hasNext())
.thenReturn(true)
.thenReturn(true)
.thenReturn(false);
when(cursor.next())
.thenReturn(doc1)
.thenReturn(doc2);
Mockito.when(collection.find(Mockito.any(BasicDBObject.class))).thenReturn(iterable);
mdmdaoimpl.viewUserData("1","bharathi");
verify(collection,times(1)).find(Mockito.any(BasicDBObject.class));
}