我想为我的Core Data模型迁移创建自动化测试。我有三个版本的模型 - 1.0,1.1和1.2。我希望每次测试都创建一个新的数据库,用假数据填充它,然后将其迁移到更新的版本,测试一路上的任何错误。我应该如何编写这样的测试?
答案 0 :(得分:0)
我通过从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)")
}
}