Where I can create an entity like so inside an XCTestCase
test just fine:
let entity = NSEntityDescription.insertNewObject(
forEntityName: String(describing: Example.self),
into: inMemoryManagedObjectContext)
But if I do it like this:
let item = Example(context: inMemoryManagedObjectContext)
A test would fail with...
failed: caught "NSInvalidArgumentException", "An NSManagedObject of
class 'myappTests.Example' must have a valid NSEntityDescription."
How am I supposed to test Core Data objects if I can't create them the way it is usually done?
I had this problem too :) The problem, I guess, is that the entities are not known yet by CoreData. So, My Solution to be able to test it was to have an instance of NSPersistantContainer while testing.
var persistentContainer: NSPersistentContainer!
override func setUp() {
super.setUp()
guard let model = CoreDataUtilities.model(withName: "ModelName") else {
return XCTFail("Model should load")
}
storeFolder = FileManager.default.temporaryDirectory.appendingPathComponent("storeDirectory", isDirectory: true)
let storeURL = storeFolder.appendingPathComponent("store.db")
let storeInfo = NSPersistentStoreDescription(url: storeURL)
storeInfo.type = NSSQLiteStoreType
persistentContainer = NSPersistentContainer(name: "ModelName", managedObjectModel: model)
persistentContainer.persistentStoreDescriptions = [storeInfo]
return
}
Now you can use CoreData the classic way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With