我想为我的核心数据模型迁移创建自动化测试。我有三个版本的模型- 1.0,1.1和1.2。我想用每个测试创建一个新的数据库,用假数据填充它,而不是将它迁移到一个更新的版本中,测试整个过程中的任何错误。我应该如何处理这样的写作测试呢?
发布于 2015-12-11 19:55:33
我通过从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)")
}
}https://stackoverflow.com/questions/34231012
复制相似问题