Skip to content

Instantly share code, notes, and snippets.

@Monntay
Last active October 18, 2019 14:41
Show Gist options
  • Select an option

  • Save Monntay/ca6d3e8cc15e5c09977217f8ba3eb3f9 to your computer and use it in GitHub Desktop.

Select an option

Save Monntay/ca6d3e8cc15e5c09977217f8ba3eb3f9 to your computer and use it in GitHub Desktop.
CoreData lightweight Migration test
// we will test the migration from version 1 to 2. the names of a person changed.
func testLightWeightMigration() {
// MARK: 1 - read and load the old model
let oldModelURL = Bundle(for: AppDelegate.self).url(forResource: "CoreDataMigrationGuide.momd/CoreDataMigrationGuide", withExtension: "mom")!
let oldManagedObjectModel = NSManagedObjectModel(contentsOf: oldModelURL)
XCTAssertNotNil(oldManagedObjectModel)
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: oldManagedObjectModel!)
try! coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
// MARK: 2 - adding a person to the old db
let person = NSEntityDescription.insertNewObject(forEntityName: "Person", into: managedObjectContext)
person.setValue("name_", forKey: "name")
person.setValue("surname_", forKey: "surname")
person.setValue(true, forKey: "teacher")
try! managedObjectContext.save()
// MARK: 3 - migrate the store to the new model version
let newModelURL = Bundle(for: AppDelegate.self).url(forResource: "CoreDataMigrationGuide.momd/CoreDataMigrationGuide 2", withExtension: "mom")!
let newManagedObjectModel = NSManagedObjectModel(contentsOf: newModelURL)
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
let newCoordinbator = NSPersistentStoreCoordinator(managedObjectModel: newManagedObjectModel!)
try! newCoordinbator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
let newManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
newManagedObjectContext.persistentStoreCoordinator = newCoordinbator
// MARK: 4 - test the migration
let newPersonRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let newPersons = try! newManagedObjectContext.fetch(newPersonRequest) as! [NSManagedObject]
XCTAssertEqual(newPersons.count, 1)
XCTAssertEqual(newPersons.first?.value(forKey: "firstname") as? String, "name_")
XCTAssertEqual(newPersons.first?.value(forKey: "lastname") as? String, "surname_")
XCTAssertEqual(newPersons.first?.value(forKey: "teacher") as? Bool, true)
XCTAssertEqual(newPersons.first?.value(forKey: "age") as? Int, nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment