核心数据迁移的自动化测试

Automated tests for Core Data Migration

我想为我的核心数据模型迁移创建自动化测试。我有模型的三个版本——1.0、1.1 和 1.2。我想为每个测试创建一个新的数据库,用假数据填充它,而不是将它迁移到更新的版本,测试过程中是否有任何错误。我应该如何编写这样的测试?

我已经通过从 mom 而不是 momd 文件加载模型解决了这个问题。示例测试如下所示:

func testMigarationFrom_1_0_To_1_1() {
    let modelUrl = NSBundle.mainBundle().URLForResource("1.0", withExtension: "mom", subdirectory: "Model.momd")!
    let model = NSManagedObjectModel(contentsOfURL: modelUrl)!
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
    let databaseUrl = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("Storage").URLByAppendingPathExtension("sqlite")
    try! coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: databaseUrl, options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true])

    let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    context.persistentStoreCoordinator = coordinator

    for i in 0..<10 {
        let entity = NSEntityDescription.insertNewObjectForEntityForName("entity", inManagedObjectContext: context) as! Entity
        entity.name = "test-\(i)"
    }

    let newModelUrl = NSBundle.mainBundle().URLForResource("1.1", withExtension: "mom", subdirectory: "Model.momd")!
    let newModel = NSManagedObjectModel(contentsOfURL: newModelUrl)!
    let newCoordinator = NSPersistentStoreCoordinator(managedObjectModel: newModel)

    do {
        try newCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: databaseUrl, options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true])
    } catch let error {
        XCTFail("Should migrate without error, got \(error)")
    }
}