Mockito FindIterable

问题描述 投票:5回答:3

正在尝试使用下面的方法编写一个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。不确定如何将虚拟/测试值分配给findIterable。

请告知。

谢谢!巴拉提

java mockito junit4 mongodb-java
3个回答
5
投票

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

遍历迭代器的某些方法时>

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

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); 

这不是一个完整的解决方案。您需要使其适应您的班级。


4
投票

您在null模拟调用中返回collection.find(...):>

FindIterable<Document> findIterable = null;
Mockito.when(collection.find(new Document())).thenReturn(findIterable);

0
投票

我想用一种通用方法来模拟Mockito.when(...).thenReturn(valuetoReturn)(与pvpkiran相同)来完成DistinctIterable答案。

NB /为了避免声纳警告,我使用内部类

© www.soinside.com 2019 - 2024. All rights reserved.