我正在使用自定义实体迁移策略为我的迁移构建映射模型,并且我真的很想为此迁移构建一些单元测试。当我运行应用程序时,迁移似乎可以正常工作,但是当我通过单元测试运行迁移时,根本不调用NSEntityMigrationPolicy子类方法。

我正在使用Xcode的内置OCUnit框架。

我的测试代码:

- (void)test1to2Migration_appIdentifierMoved {
  [self createVersion1Store];

  // TODO Perform migration
  NSManagedObjectModel *version1Model = [self version1Model];
  NSManagedObjectModel *version2Model = [self version2Model];

  NSError *error = nil;
  NSMappingModel *mappingModel = [NSMappingModel
      inferredMappingModelForSourceModel:version1Model
      destinationModel:version2Model error:&error];
  STAssertNotNil(mappingModel, @"Error finding mapping model: %@", error);

  NSMigrationManager *migrationManager =
      [[[NSMigrationManager alloc]
        initWithSourceModel:version1Model
        destinationModel:version2Model]
       autorelease];

  BOOL migrationSucceeded =
      [migrationManager migrateStoreFromURL:self.version1StoreURL
           type:NSSQLiteStoreType
           options:nil
           withMappingModel:mappingModel
           toDestinationURL:self.version2StoreURL
           destinationType:NSSQLiteStoreType
           destinationOptions:nil
           error:&error];
  STAssertTrue(migrationSucceeded, @"Error migrating store: %@", error);

  // TODO Verify appIdentifier is moved from Project to its Tests

  [self deleteTempStores];
}

我的映射模型指定了一个自定义的NSEntityMigrationPolicy,它定义了-createRelationshipsForDestinationInstance:entityMapping:manager:error:方法,但是从未从单元测试中调用我的策略。当我运行迁移时,模型被修改为新版本-预期的属性显示在正确的位置。

有什么想法可以使我的迁移策略在单元测试中起作用吗?

最佳答案

问题出在网上

NSMappingModel *mappingModel = [NSMappingModel
  inferredMappingModelForSourceModel:version1Model
  destinationModel:version2Model error:&error];

如果我将其更改为
NSMappingModel *mappingModel = [NSMappingModel
  mappingModelFromBundles:@[[NSBundle bundleForClass:[MyTestClass class]]]
  forSourceModel:version1Model destinationModel:version2Model];

然后测试可以正常运行。

关于ios - 如何对核心数据迁移进行单元测试?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11959447/

10-10 20:32
查看更多