Swift NSManagedObject subclasses, namespaces and testing

I have an app on which I'm trying to implement unit tests. I'm using swift 2.0, Xcode 7 beta 3 and I have several NSManagedObject subclasses which I'm trying to use in unit tests. I'm having the following problems that are preventing me from properly testing...


I'm creating an instance of my class and inserting the newly created object with the following line of code:

let entityName = NSEntityDescription.insertNewObjectForEntityForName("EntityName", inManagedObjectContext: context) as! EntityName


I'm using the NSManageObject generated subclasses with the Module set to the default "Current Product Module".

If I use the defaults without changing anything I get the following error:

Could not cast value of type 'NSManagedObject_EntityName_' (0x7a990b30) to 'AppName.EntityName' (0x101c2ee8).

If I run the code in test mode I get this error:

Could not cast value of type 'NSManagedObject_EntityName_' (0x7a990b30) to 'AppNameTests.EntityName' (0x101c2ee8).

If I blank out the Module for my entities so the placeholder says "None", the app runs fine while debugging and using on a device, but when testing I get the following error:

Could not cast value of type 'AppName.EntityName (0x7a0aabe8) to 'AppNameTests.EntityName' (0x1023bee8).


So, how does one define the module for a Core Data NSManagedObject subclass in swift so that it can be both run and tested?

Accepted Reply

Ok, I figured it out! It's not exactly intuitive though. First, I had to comment out the @objc(EntityName) line in the NSManagedObject subclasses. Then I went back to the default Module defined in the xcdatamodeld (Current Project Module). Then I had to ensure that only my test classes (and NONE of the NSManagedObject subclasses or any other source files) were compiled as part of my test project (this was critical) and @testable import AppName in my test project class files. Now it never trys to use these classes in the AppNameTests module, only AppName and the test projects can only call public or internal code...therefore all is right in the universe, yay!

Replies

Sorry, I forgot to mention I've tried all of these scenarios with and without @objc(EntityName)

Ok, I figured it out! It's not exactly intuitive though. First, I had to comment out the @objc(EntityName) line in the NSManagedObject subclasses. Then I went back to the default Module defined in the xcdatamodeld (Current Project Module). Then I had to ensure that only my test classes (and NONE of the NSManagedObject subclasses or any other source files) were compiled as part of my test project (this was critical) and @testable import AppName in my test project class files. Now it never trys to use these classes in the AppNameTests module, only AppName and the test projects can only call public or internal code...therefore all is right in the universe, yay!