Spring 引导模拟 Mongodb setOnInsert

Spring Boot Mocking Mongodb setOnInsert

我有以下 MongoDB 使用 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();
    });
  }

但是我不确定如何为上面使用 setOnInsert 的代码编写一个好的模拟测试 非常感谢任何帮助

你必须模拟整个数据库class和集合

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

正如在这个问题中评论的那样: unit testing with mongo db and java