There are quite a few subjects on this already, but I have yet to find a solution that is workable for Swift (Xcode 6.2).
To test Core Data backed classes in Swift, I generate new Managed Object Contexts that I then inject into my classes.
//Given
let testManagedObjectContext = CoreDataTestComposer.setUpInMemoryManagedObjectContext()
let testItems = createFixtureData(testManagedObjectContext) as [TestItem]
self.itemDateCoordinator.managedObjectContext = testManagedObjectContext
//When
let data = self.itemDateCoordinator.do()
//Then
XCTAssert(data.exists)
The issue comes from passing a MOC created in the Test to the class that's doing. Because entity classes are namespaced, Core Data won't fetch your the appropriate ManagedObject subclass and instead hands back a NSManagedObject
set. When looping or doing anything with these objects (which in your class would be an array of test items ([TestItem]
).
For example, the offending class ItemDateCoordinator
would execute this loop (after pulling the relevant data from a NSFetchRequest
)"
for testItem in testItems {
testItem.doPart(numberOfDays: 10)
}
would result in:
fatal error: NSArray element failed to match the Swift Array Element type
Also, I have come across a collection of information without much of a solid answer:
- To cast entities when creating them, I have been using a solution by Jesse, but that doesn't work on a larger scope of testing.
- A solution has been posted on another question that involved swapping out the classes at runtime, but that hasn't worked for me with entity inheritance.
- Is there another method to testing your objects with Core Data in this case? How do you do it?