title: NSPersistentContainer & UnitTests with iOS10
body: <p>I have an issue with my Core Data setup for Unit Tests.</p>
  
  <p>I use the default/new Core Data stack setup in my AppDelegate</p>
  
  <pre><code>class AppDelegate: UIResponder, UIApplicationDelegate {
      lazy var persistentContainer: NSPersistentContainer = {
          let container = NSPersistentContainer(name: "GenericFirstFinder")
          container.loadPersistentStores(completionHandler: { (storeDescription, error) in
              if let error = error as NSError? {
                  fatalError("Unresolved error \(error), \(error.userInfo)")
              }
          })
          return container
      }()
  }
  </code></pre>
  
  <p>And for testing I have a custom function to create a managed context</p>
  
  <pre><code>func setupInMemoryManagedObjectContext() -&gt; NSManagedObjectContext {
      let container = NSPersistentContainer(name: "GenericFirstFinder")
  
      let description = NSPersistentStoreDescription()
      description.type = NSInMemoryStoreType
      container.persistentStoreDescriptions = [description]
  
      container.loadPersistentStores(completionHandler: { (storeDescription, error) in
          if let error = error as NSError? {
              fatalError("Unresolved error \(error), \(error.userInfo)")
          }
      })
  
      return container.viewContext
  }
  </code></pre>
  
  <p>I have an extension to find the first item given a predicate.</p>
  
  <pre><code>extension NSManagedObject {
      class func first(with predicate: NSPredicate?, in context: NSManagedObjectContext) throws -&gt; Self? {
          return try _first(with: predicate, in: context)
      }
  
      fileprivate class func _first&lt;T&gt;(with predicate: NSPredicate?, in context: NSManagedObjectContext) throws -&gt; T? where T: NSFetchRequestResult, T: NSManagedObject {
          let fetchRequest = self.fetchRequest()
          fetchRequest.fetchLimit = 1
          fetchRequest.predicate = predicate
          let results = try context.fetch(fetchRequest)
          return results.first as? T
      }
  }
  </code></pre>
  
  <p>Here's the issue.</p>
  
  <p>This test passes:</p>
  
  <pre><code>func testExample() {
      let context = setupInMemoryManagedObjectContext()
      let entity = try! Entity.first(with: nil, in: context)
      XCTAssertEqual(entity, nil)
  }
  </code></pre>
  
  <p>but if the persistentContainer loading is triggered in didFinishLaunchingWithOptions</p>
  
  <pre><code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -&gt; Bool {
      // Override point for customization after application launch.
      let context = persistentContainer.viewContext // end of laziness
      return true
  }
  </code></pre>
  
  <p>then I get the following error</p>
  
  <blockquote>
    <p>failed: caught "NSInvalidArgumentException",
    "executeFetchRequest:error:  is not a valid NSFetchRequest."</p>
  </blockquote>
  
  <p>The error comes specifically from this line in _first()</p>
  
  <pre><code>let fetchRequest = self.fetchRequest() // fetchRequest  is &lt;uninitialized&gt; in that case
  </code></pre>
  
  <p>But if I modify the test to create an entity first, the test runs fine again (the XCTAssertEqual is different of course…):</p>
  
  <pre><code>func testExample() {
      let context = setupInMemoryManagedObjectContext()
      let firstEntity = Entity(context: context)
      let entity = try! Entity.first(with: nil, in: context)
      XCTAssertEqual(entity, firstEntity)
  }
  </code></pre>
  
  <p>So for some reason, creating a new entity (without saving the context) seems to put things back in order.</p>
  
  <p>I guess my stack setup for testing is screwed up, but I haven't figured out why. Do you understand what's happening and what is the proper way to set things up?</p>
  
  <p>I'm using Xcode 8.3, Swift 3.1 and the deployment target is iOS 10.3.</p>