【问题标题】:Automated tests for Core Data Migration核心数据迁移的自动化测试
【发布时间】:2015-12-11 19:21:32
【问题描述】:

我想为我的 Core Data 模型迁移创建自动化测试。我有模型的三个版本 - 1.0、1.1 和 1.2。我想在每次测试时创建一个新数据库,用假数据填充它,然后将其迁移到更新的版本,并在此过程中测试任何错误。我应该如何编写这样的测试?

【问题讨论】:

    标签: ios xcode core-data automated-tests core-data-migration


    【解决方案1】:

    我已经通过从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)")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 2011-03-02
      • 2012-02-28
      • 1970-01-01
      相关资源
      最近更新 更多