mercredi 1 juillet 2015

Unit test with example Core Data

This is start of my XCTestCase class:

var moc: NSManagedObjectContext!

    override func setUp() {
        super.setUp()

        moc = self.setUpInMemoryManagedObjectContext()
        self.fillManagedObjectContextWithExampleData(moc)
    }

    func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {

        let modelName = "DetoxMe"
        let modelURL = NSBundle.mainBundle().URLForResource(modelName, withExtension:"momd")!
        let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)!

        let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
        persistentStoreCoordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil, error: nil)

        let managedObjectContext = NSManagedObjectContext()
        managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator

        return managedObjectContext
    }

    func fillManagedObjectContextWithExampleData(context: NSManagedObjectContext) {
        // var firstSC = NSEntityDescription..insertNewObjectForEntityForName("StaticContent", inManagedObjectContext: context) as! StaticContent
        var staticContentEntity = NSEntityDescription.entityForName("StaticContent", inManagedObjectContext: context)!

        var firstSC = StaticContent(entity: staticContentEntity, insertIntoManagedObjectContext: context)
        firstSC.name = "First Name"

        var secondSC = StaticContent(entity: staticContentEntity, insertIntoManagedObjectContext: context)
        secondSC.name = "Second Name"

        var error: NSError? = nil

        if context.save(&error) {
            return
        }
    }

I just want to create managedObjectContext (in memory, just for testing) and fill it with example data. So I could use:

managedObjectContext.executeFetchRequest(fetchRequest, error: nil) as! [StaticContent]

in my unit tests. It executes but when I call function which takes [StaticContent] I got an error:

fatal error: NSArray element failed to match the Swift Array Element type

So what is a problem with this? My function which I call works fine. When I using it in my app and not in unit tests I don't have problem. So what I am doing wrong?

Aucun commentaire:

Enregistrer un commentaire