Chapter 7: Unit Testing - occasional crash

I’m facing this issue on the screenshot every second time or so. Happens on chapter 7’s starter project with a few added tests.

Here’re some tips that this relates to wrong module name being used in testing environment: http://stackoverflow.com/a/30468417/1675788
I’ve converted SO answer swift 3 , fed it to NSPersistentContainer's init and it didn’t help:

lazy var managedObjectModel: NSManagedObjectModel =
    {
      let modelURL = Bundle.main.url(forResource: self.modelName, withExtension: "momd")
      let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL!)
      
      let environment = ProcessInfo.processInfo.environment
      
      let isTest:Bool
      if let count = environment["XCTestConfigurationFilePath"]?.characters.count, count > 0 { isTest = true }
      else { isTest = false }
      
      let moduleName = (isTest) ? "CampgroundManagerTests" : "CampgroundManager"
      
      // Create a new managed object model with updated entity class names
      var newEntities = [] as [NSEntityDescription]
      for entity in managedObjectModel!.entities
      {
        let newEntity = entity.copy() as! NSEntityDescription
        newEntity.managedObjectClassName = "\(moduleName).\(entity.name)"
        newEntities.append(newEntity)
      }
      let newManagedObjectModel = NSManagedObjectModel()
      newManagedObjectModel.entities = newEntities
      
      return newManagedObjectModel
  }()

I also see this in the top of my console output:

CoreData: warning: Unable to load class named ‘CampgroundManagerTests.Optional(“CampSite”)’ for entity ‘CampSite’. Class not found, using default NSManagedObject instead.

What’s the simplest way to fix this error?
Thanks :slight_smile:

Sorry, that code from Stackoverflow looks a bit weird to me… What version of the CoreData Book do you have. I had no Problem with the Tests in version 3.1 - all was straight forward… (in this Part)

Looks like it basically prepend managedObjectClassName with module name (that was the idea of the SO post). I have Core_Data_by_Tutorials_v3.1.pdf