托管对象上下文 nil restkit while unitTesting

managed object context nil restkit while unitTesting

我正在使用通过 cocoapods 集成的 restkit (0.24.1) 为我的应用程序开发单元测试:

pod "RestKit/Testing", "~> 0.24.1"
pod "RestKit", "~> 0.24.1"

我收到一条错误消息,指出 managedObjectContext 为 nil。我不敢苟同,因为我已经有很多使用相同对象上下文的单元测试,而且它们似乎都可以工作……:/

Restkit 设置:

lazy var persistentStoreCoordinator: RKManagedObjectStore? = {
    var coordinator = RKManagedObjectStore(managedObjectModel: self.managedObjectModel)
    self.objectManager!.managedObjectStore = coordinator

    coordinator.createPersistentStoreCoordinator()

    var storePath: NSString = RKApplicationDataDirectory().stringByAppendingPathComponent(self.storeFilename)

    var e: NSError?
    coordinator.addSQLitePersistentStoreAtPath(storePath as String, fromSeedDatabaseAtPath: nil, withConfiguration: nil,
        options: [
            NSInferMappingModelAutomaticallyOption: true,
            NSMigratePersistentStoresAutomaticallyOption: true
        ], error: &e)

    if(e != nil){
            var error: NSError? = nil
            coordinator = nil
            // Report any error we got.
            let dict = NSMutableDictionary()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data."
            dict[NSUnderlyingErrorKey] = error
            error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
            Logger.Error("Serious error \(error), \(error!.userInfo)")
            abort()
    }

    coordinator.createManagedObjectContexts()
    coordinator.managedObjectCache = RKInMemoryManagedObjectCache(managedObjectContext: coordinator.persistentStoreManagedObjectContext)

    return coordinator
    }()

单元测试:

class TestRestMappers: XCTestCase {

    let rootEndpoint = RootEndpoint()

    override func setUp() {
        super.setUp()

        let testTargetBundle = NSBundle(identifier: "anita-borg.malaria-iosTests")
        RKTestFixture.setFixtureBundle(testTargetBundle)
    }

    func testRootEndpointMapper() {
        let parsedJson: AnyObject? = RKTestFixture.parsedObjectWithContentsOfFixture("api.json")

        let mapping = rootEndpoint.mapping

        let test = RKMappingTest(forMapping: mapping, sourceObject: parsedJson, destinationObject: nil)

        test.addExpectation(RKPropertyMappingTestExpectation(sourceKeyPath: "users", destinationKeyPath: "users"))

        XCTAssertTrue(test.evaluate)
    }
}

我从控制台得到的错误信息是:

*** Assertion failure in -[RKMappingTest dataSourceForMappingOperation:], (...): error: 
-[malaria_iosTests.TestRestMappers testRootEndpointMapper] : XCTAssertTrue failed: throwing "Cannot test an `RKEntityMapping` with a nil managed object context." - 

Test Case '-[malaria_iosTests.TestRestMappers testRootEndpointMapper]' failed (0.010 seconds).

我连接商店的映射片段:

let managedObjectStore: RKManagedObjectStore = CoreDataStore.sharedInstance.persistentStoreCoordinator!
let rootMap = RKEntityMapping(forEntityForName: name, inManagedObjectStore: managedObjectStore)

我已经在很多地方搜索了问题的根源,但似乎找不到解决方案。

提前致谢

编辑:

NSManagedObjectContext:

lazy var backgroundContext: NSManagedObjectContext? = {
    let coordinator = self.store.persistentStoreCoordinator?.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }

    var backgroundContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
    backgroundContext.persistentStoreCoordinator = coordinator
    return backgroundContext
    }()

测试需要配置。一般来说,你应该假设如果你没有明确地给测试一些信息那么它就没有任何信息。因此,您需要为测试提供一个可以使用的上下文(在您的特定情况下可能还需要一个数据源)。

test.managedObjectContext = ...