如何在XCTestCase中测试NSPersistentDocument?

时间:2015-12-02 21:07:01

标签: swift cocoa core-data nspersistentdocument

我刚刚使用Core Data启动基于OS X文档的应用程序。为了测试我的模型关系,我想创建一些NSManagedObject实体,将它们保存到文件中,然后在XCTestCase对象中读取它们。使用下面的代码,我可以在托管对象上下文中创建实体,但我无法弄清楚如何创建一个正常运行的持久性存储协调器和/或保存到文件。

class MyTests: XCTestCase {

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

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

    //...//
}

1 个答案:

答案 0 :(得分:0)

我上面的初步方法问题是我在使用managedObjectContext之前获得了configurePersistentStoreCoordinatorForURL。一旦我解决了这个问题,解决方案就相当简单。

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)")
        }
    }

}