1

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

1
  • 1
    It is better to use a BulWrite operation when you want to write/update documents created based upon data from a Java collection (instead using a for-loop now). Bulk write allows single database server call and a single result, and is efficient. Commented Mar 12, 2022 at 9:56

1 Answer 1

1
+100

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.