由于Null指针,Java Junit Mock因MongoDB而失败

时间:2017-06-06 15:27:58

标签: java junit

我正在为mongoDB读操作做单元测试用例。当我尝试模拟查找操作时,我得到一个NullPointerException

   public class MongoQueriertest {

        HelperUtil testhelper = new HelperUtil();

        DBCollection feedCollection;
        DBCursor curr;

        @Test(expected=NullPointerException.class)
        public void test_MongoQuerier ()throws Exception {

            MongoQuerier query = new MongoQuerier();
            FindIterable iterable = mock(FindIterable.class);
            curr =  mock(DBCursor.class);
            BasicDBObject obj = mock(BasicDBObject.class);
            when(feedCollection.find(obj)).thenReturn((DBCursor) iterable);
            query.getMaxId("String");   
        }

    }

Method to test
 public String getMaxId(String dataVersion) throws Exception{
    String  maxJobId = "1";

    try {  

    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("instance", dataVersion);

      DBCursor curr = feedCollection.find(whereQuery);  //.sort(new BasicDBObject(mongoDBSetting.maxIdField.replace("$", ""), -1)).limit(1);

      //AggregationOutput cursor = feedCollection.find().sort(""); //.aggregate(Arrays.asList(query));
      while (curr.hasNext()) {
//      String mid = curr.next().get(mongoDBSetting.maxIdField.replace("$", "")).toString();
//      
//      mid = mid.replace("", "");

        maxJobId =  curr.next().get(mongoDBSetting.maxIdField.replace("$", "")).toString(); //Integer.parseInt(mid);
       }

     /* for (DBObject result : curr.results()) {
        maxJobId = Integer.parseInt(result.get(mongoDBSetting.maxIdField.replace("$", "")).toString());
            break;
      }*/ 
    }
    catch (Exception ex) {
      AppLogger.EventLogger.error("Exception occured selecting maxid in mongoDB. Exception -" + ex.getMessage().toString());
      throw new Exception(ex.getMessage().toString());
    }
    return maxJobId;
  }

请告诉我我失踪的地方。我添加了需要测试用例的方法。

1 个答案:

答案 0 :(得分:0)

您在feedCollection上记录了一个实际上没有被模拟的模拟行为

when(feedCollection.find(obj)).thenReturn((DBCursor) iterable);

对象是null

因此feedCollection.find(obj)会抛出nullPointerException

实际上你已经嘲笑了这两个对象:

 curr =  mock(DBCursor.class);
 BasicDBObject obj = mock(BasicDBObject.class);

除了模拟对象是模拟方法但要使其工作的第一步之外,模拟对象应该与被测对象相关联。
事实并非如此。您可以创建要测试的MongoQuerier对象,但不要将mocks对象设置为它。

MongoQuerier query = new MongoQuerier();

您应该创建一个要使用模拟对象进行测试的对象实例。

例如,通过这种方式将模拟对象与其关联。

MongoQuerier query = new MongoQuerier(mockObject, mockObject2, ...);