托管对象上下文nil restkit而unitTesting

时间:2015-06-21 13:00:39

标签: swift unit-testing restkit cocoapods nsmanagedobjectcontext

我正在使用使用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
    }()

1 个答案:

答案 0 :(得分:1)

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

test.managedObjectContext = ...