Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCTestCase for CoreData fails with "could not locate the entity for myappTests.Example"

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?

like image 381
sanmai Avatar asked Aug 09 '17 02:08

sanmai


1 Answers

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.

like image 120
LastMove Avatar answered Nov 13 '22 20:11

LastMove