如何对Core Data迁移进行单元测试?

时间:2012-08-14 19:30:54

标签: ios unit-testing core-data ocunit core-data-migration

我正在使用自定义实体迁移策略为我的迁移构建映射模型,我真的想为此迁移构建一些单元测试。当我运行应用程序时,迁移似乎正常工作,但当我通过单元测试运行迁移时,根本不会调用我的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];
}

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

我有什么想法可以让我的迁移政策在单元测试中运行?

2 个答案:

答案 0 :(得分:4)

问题原因在于

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

如果我将其更改为

NSMappingModel *mappingModel = [NSMappingModel
  mappingModelFromBundles:@[[NSBundle bundleForClass:[MyTestClass class]]]
  forSourceModel:version1Model destinationModel:version2Model];

然后测试功能正常。

答案 1 :(得分:4)

Swift 3

为模型文件名替换变量 modelName modelNameVersionFormatString

notification_builder_id