I'm trying to create test cases for my Core Data driven view controllers. One problem I run into is managing temporary persistent containers when the test are running concurrently. I try to get around this by keeping a static copy of the NSManagedObjectModel to pass around the test cases, but it only kind of works. Here is the code -
class CoreDataTestCase: XCTestCase {
static var model: NSManagedObjectModel?
var mockPersistentContainer: NSPersistentContainer!
override func setUp() {
print("setUp")
super.setUp()
if let model = CoreDataTestCase.model {
mockPersistentContainer = NSPersistentContainer(name: "MySchema", managedObjectModel: model)
} else {
mockPersistentContainer = NSPersistentContainer(name: "MySchema")
CoreDataTestCase.model = mockPersistentContainer.managedObjectModel
}
// mockPersistentContainer.persistentStoreDescriptions[0].url = URL(fileURLWithPath: "/dev/null")
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
description.shouldAddStoreAsynchronously = false // Make it simpler in test env
mockPersistentContainer.persistentStoreDescriptions = [description]
mockPersistentContainer.loadPersistentStores { (_, error) in
XCTAssertNil(error)
}
...
When I run the tests individually they work, but when I run them concurrently I get the error
CoreData: warning: View context accessed for persistent container MySchema with no stores loaded CoreData: warning: 'MyEntity' (0x600002fa6260) from NSManagedObjectModel (0x600003bc8690) claims 'MySchema.MyEntity'. 2021-06-09 13:43:27.663078-0400 MySchema[76742:12179736] [error] error: +[MySchema.MyEntity entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass CoreData: error: +[MySchema.MyEntity entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass 2021-06-09 13:43:27.666042-0400 MySchema[76742:12179736] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'MySchema.MyEntity' must have a valid NSEntityDescription.'