Search code examples
mongodbmockitospring-data-mongodb

Spring Boot Mocking Mongodb setOnInsert


I have the following MongoDB code that uses setonInsert

  public void populateRecords(Set<String> recNames) {
    MongoTemplate mongoTemplate = mongoHolder.getMongoTemplate();
    dbNames.forEach(recName -> {
      Update update = new Update()
          .setOnInsert(Fields.recName, recName)
          .setOnInsert(Fields.lastUpdated, LocalDateTime.MIN);
      mongoTemplate.update(RecordNameDocument.class)
          .apply(update)
          .upsert();
    });
  }

However Im not sure how to write a good Mock test for above code that uses setOnInsert Any help is highly appreciated


Solution

  • You have to mock the entire database class and collections

    Mongo mongo = PowerMockito.mock(Mongo.class);
    DB db = PowerMockito.mock(DB.class);
    DBCollection dbCollection = PowerMockito.mock(DBCollection.class);
    
    PowerMockito.when(mongo.getDB("foo")).thenReturn(db);
    PowerMockito.when(db.getCollection("bar")).thenReturn(dbCollection);
    
    MyService svc = new MyService(mongo); // Use some kind of dependency injection
    svc.getObjectById(1);
    
    PowerMockito.verify(dbCollection).findOne(new BasicDBObject("_id", 1));
    

    as commented in this question: unit testing with mongo db and java