Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!