Swift cannot test core data in Xcode tests?

前端 未结 5 801
失恋的感觉
失恋的感觉 2021-02-02 12:42

I am working on a iOS project that uses core data. I am using swift. The Core Data stack is setup right and all seems to be fine. I have created a class for an entity (NSManage

5条回答
  •  天命终不由人
    2021-02-02 13:35

    It's because the CoreData framework is still in Objective-C. Swift uses namespaced-classes, so for CoreData to find your swift classes you have to specify the Class name with it's namespace like this:

    enter image description here

    The problem your will have is that your App does not have the same namespace as when you are running you tests. . vs Tests.

    EDIT: Solution for running as App and Tests

    I just wrote a piece of code to solve the . vs Tests. issue. The solution I use at this time (Xcode 6.1) is to NOT fill the Class field in the CoreData UI (shown above), and to do it in code instead.

    This code will detect if you are running as App vs Tests and use the right module name and update the managedObjectClassName.

    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional...
        let modelURL = NSBundle.mainBundle().URLForResource("Streak", withExtension: "momd")!
        let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)!
    
        // Check if we are running as test or not
        let environment = NSProcessInfo.processInfo().environment as [String : AnyObject]
        let isTest = (environment["XCInjectBundle"] as? String)?.pathExtension == "xctest"
    
        // Create the module name
        let moduleName = (isTest) ? "StreakTests" : "Streak"
    
        // Create a new managed object model with updated entity class names
        var newEntities = [] as [NSEntityDescription]
        for (_, entity) in enumerate(managedObjectModel.entities) {
            let newEntity = entity.copy() as NSEntityDescription
            newEntity.managedObjectClassName = "\(moduleName).\(entity.name)"
            newEntities.append(newEntity)
        }
        let newManagedObjectModel = NSManagedObjectModel()
        newManagedObjectModel.entities = newEntities
    
        return newManagedObjectModel
    }()
    

提交回复
热议问题