Multiple Warnings when running Unit Tests in Sample app

I had a little time to mess around with this. At first I thought I wasn’t getting the warnings, but when I checked, I was. Final Project, untouched, Xcode 10.2.1.

StackOverflow has some stuff on this. The warning occurs because two complete core data stacks are being created: the test stack, but also the regular stack. application(didFinishLaunchingWithOptions:) gets called, and the regular CoreDataStack gets created and passed around to the view controllers, even though they don’t get shown. There is probably some way to suppress that using test scheme options or something, but the simplest way is detailed at this GitHub link:

When you use the convenience init for your managed objects, it searches all the managed object models, and gives a warning if it finds two occurrences of your entity name. I guess that is okay, since I didn’t know the regular CoreDataStack was also loading, and it is good be alerted to it. It then uses the definition associated with the passed in context, so it works out fine and the tests succeed.

You can avoid the warnings by using a more explicit init, which is easiest to do if you add a new convenience init to NSManagedObject:

import CoreData

public extension NSManagedObject {
  convenience init(using usedContext: NSManagedObjectContext) {
    let name = String(describing: type(of: self))
    let entity = NSEntityDescription.entity(forEntityName: name, in: usedContext)!
    self.init(entity: entity, insertInto: usedContext)
  }
}

This makes the entity description specific to the passed in context, so there is no ambiguity, and therefore no more warning messages.

The corresponding code changes are in the CamperService, CampSiteService, and ReservationService, in the lines creating the Camper, CampSite, or Reservation respectively:

    let camper = Camper(using: managedObjectContext)
///
    let campSite = CampSite(using: managedObjectContext)
///
    let reservation = Reservation(using: managedObjectContext)