swiftcocoacore-datanspersistentdocument

How to test NSPersistentDocument in XCTestCase?


I'm just starting an OS X document-based app using Core Data. To test my model relationships, I'd like to create some NSManagedObject entities, save them to a file, and read them back in an XCTestCase object. Using code like below, I can create entities in the managed object context, but I cannot figure out how to create a functioning persistent store coordinator and/or save to a file.

class MyTests: XCTestCase {

    var doc: Document!
    var moc: NSManagedObjectContext!
    //...//

    override func setUp() {
        super.setUp()
        doc = Document()
        moc = doc.managedObjectContext
    }

    //...//
}

Solution

  • Problem with my initial approach above was that I was getting the managedObjectContext before using configurePersistentStoreCoordinatorForURL. Once I resolved that, the solution was fairly straightforward.

    class DocTests : XCTestCase {
    
        let testFileURL = NSURL.fileURLWithPath("/Users/Me/Temp/DocTests", isDirectory: false)
    
        override func setUp() {
            super.setUp()
        }
    
        func testWriteAndRead() {
    
            writeSimpleTestDocument()
    
            let doc = Document()        
            do {
                try doc.readFromURL(testFileURL, ofType: "mydoctype")
            } catch let error as NSError {
                print("Failed to read, \(error), \(error.userInfo)")
            }
    
            let moc = doc.managedObjectContext!
    
            // fetch from moc and verify test entities here ...
            // ...
        }
    
    
        func writeSimpleTestDocument() {
    
            // if test document exists, delete it
            let fm = NSFileManager.defaultManager()
    
            if fm.fileExistsAtPath(testFileURL.path!) {
                do {
                    try fm.removeItemAtURL(testFileURL)
                } catch let error as NSError {
                    print("Failed to remove, \(error), \(error.userInfo)")
                }
            }
    
            let doc = Document()
    
            do {
                try doc.configurePersistentStoreCoordinatorForURL(testFileURL, ofType: "mydoctype", modelConfiguration: nil, storeOptions: nil)
            } catch let error as NSError {
                print("Failed to configure coordinator, \(error), \(error.userInfo)")
            }
    
            let moc = doc.managedObjectContext!
    
            // create test entities in moc here ...
            // ...
    
            do {
                try moc.save()
            } catch let error as NSError {
                print("Failed to save, \(error), \(error.userInfo)")
            }
        }
    
    }