我正在尝试测试以下方法。但是,我得到了空指针异常

时间:2019-02-14 11:52:38

标签: java junit mockito

我为集合指定了空值,即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); 
}

1 个答案:

答案 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));
}