skip to content

In Core Data unit tests, how do you build a fresh stack for every test, and when is NSInMemoryStoreType the wrong store type?

level: middleimportance: must knowfreq 60%

answer

  1. nothing on disk, nothing shared
  2. load the model only once
  3. change the type or the URL
  4. SQLite pointed at /dev/null
  5. batch requests need the SQLite store

basics

~10 s

Create a new NSPersistentContainer per test from one shared model, with an NSInMemoryStoreType description or a SQLite store at /dev/null. The in-memory type cannot run SQLite-only work such as batch requests; /dev/null SQLite can.

solid answer

~40 s

Each test builds its own `NSPersistentContainer(name:managedObjectModel:)` whose single description keeps nothing on disk, so no test sees another's rows. Pass the same `NSManagedObjectModel` instance every time: loading the compiled model again per test leaves several entity descriptions claiming one `NSManagedObject` subclass, and Core Data warns that `+entity` can't tell them apart. For the store, either set `description.type = NSInMemoryStoreType`, or keep the default SQLite type and set the URL to `/dev/null`, which gives an empty SQLite store per container. The in-memory type is a separate store type, not SQLite in RAM: an `NSBatchDeleteRequest` or `NSBatchUpdateRequest` against it raises an exception, and query generations need SQLite in WAL mode. Use `/dev/null` when the code under test relies on SQLite behaviour.

code

swift · 24 lines
swift
import CoreData

enum TestStack {
    // Load the compiled model once; every test container shares this instance.
    static let model: NSManagedObjectModel = {
        guard let url = Bundle.main.url(forResource: "FieldSales", withExtension: "momd"),
              let model = NSManagedObjectModel(contentsOf: url) else {
            fatalError("FieldSales.momd not found")
        }
        return model
    }()

    static func makeContainer() -> NSPersistentContainer {
        let container = NSPersistentContainer(name: "FieldSales", managedObjectModel: model)
        // A SQLite store at /dev/null: empty every time, never touches disk,
        // and still runs SQLite-only work such as NSBatchDeleteRequest.
        let description = NSPersistentStoreDescription(url: URL(fileURLWithPath: "/dev/null"))
        container.persistentStoreDescriptions = [description]
        container.loadPersistentStores { _, error in
            if let error { fatalError("Test store failed to load: \(error)") }
        }
        return container
    }
}

go deeper

for a junior

Know that tests need their own stack and that NSInMemoryStoreType keeps the store off disk.

for a middle

Explain the /dev/null SQLite alternative, why the model is loaded once and passed with init(name:managedObjectModel:), and what the entity-disambiguation warning means.

for a senior

Pick the fixture from what the code uses: batch requests, query generations and other SQLite-only features crash or degrade on the in-memory type, so those tests need SQLite at /dev/null.

for a principal

Set one shared test-stack helper for the team so fixtures don't drift, and decide which suites must run on SQLite to match production behaviour.

## Why each test needs its own stack A unit test that saves into the app's real store leaves rows behind for the next test, depends on what the simulator already holds, and can corrupt a developer's data. The fix is a **new Core Data stack per test** whose store starts empty and disappears with the container. Everything else about the stack (the model, the entity classes, the code that fetches and saves) stays the production one, so the test still exercises real behaviour. ## The store types iOS offers | Store type | String constant | `NSPersistentStore.StoreType` (iOS 15) | On disk | Notes | |---|---|---|---|---| | SQLite | `NSSQLiteStoreType` | `.sqlite` | A `.sqlite` file plus `-wal` and `-shm` files | The default; batch requests and query generations need it | | Binary | `NSBinaryStoreType` | `.binary` | One file | A single-file format; batch requests do not run on it | | In-memory | `NSInMemoryStoreType` | `.inMemory` | Nothing | Gone when the coordinator goes | `NSXMLStoreType` exists only on macOS; the header marks it unavailable on iOS. `NSPersistentStoreDescription.type` is a `String`, so a description takes the string constants; the `StoreType` struct is what the Swift coordinator methods such as `destroyPersistentStore(at:type:options:)` take. ## Two ways to keep a test store off disk - **In-memory description.** Create `NSPersistentStoreDescription()`, set `type = NSInMemoryStoreType`, assign it to `persistentStoreDescriptions` and load. No URL is needed. - **SQLite at `/dev/null`.** Keep the default SQLite type and set the description's URL to `URL(fileURLWithPath: "/dev/null")`. Each container that loads it gets its own empty SQLite store, and nothing reaches the file system. ```swift import CoreData func inMemoryDescription() -> NSPersistentStoreDescription { let description = NSPersistentStoreDescription() description.type = NSInMemoryStoreType return description } ``` ## What the in-memory type cannot do The in-memory store is a different store implementation from SQLite, so features built on the SQLite store don't come with it: - **Batch requests.** Apple documents `NSBatchDeleteRequest` as available only with a SQLite store. Executing it, an `NSBatchUpdateRequest` or an `NSBatchInsertRequest` against an in-memory store raises `NSInternalInconsistencyException` with the reason "Unknown command type", so the test crashes instead of failing an assertion. - **Query generations.** Pinning a context with `setQueryGenerationFrom(_:)` needs a SQLite store in WAL journal mode; on other stores the context falls back to unpinned reads. - **Core Spotlight integration and CloudKit mirroring.** Both are documented as SQLite-only. If the code under test uses any of these, the `/dev/null` SQLite store is the right fixture. ## Load the model once The second common trap is the model. Calling `NSPersistentContainer(name:)` in every test loads the compiled model again each time, and every copy maps its entities to the same `NSManagedObject` subclasses. Core Data then logs: `CoreData: warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'Order' so +entity is unable to disambiguate.` After that, `Order(context:)` and `Order.entity()` can resolve to an entity from a model other than the one your container uses. The fix: 1. Load the `NSManagedObjectModel` once, in a `static let`. 2. Build every test container with `init(name:managedObjectModel:)`, passing that instance. 3. Give each test its own container and let it go out of scope in `tearDown`, rather than deleting rows from a shared one. ## Using the helper in a test With the model and store decided, a test class follows a fixed shape: - `setUp` calls the helper and keeps the container in a property; `tearDown` sets it to `nil`, which discards the store. - Code that takes a context or a container as a parameter can be tested directly; code that reaches for a global stack needs that dependency injected first. - Tests that check what a fetch or a save does can run on `viewContext`; tests of background work create contexts from the same test container. - Tests of an import that ends in an `NSBatchInsertRequest` or `NSBatchDeleteRequest` use the `/dev/null` SQLite fixture, so the batch work runs exactly as on a device. - Code that builds its own store URL, such as an app group location, takes the URL as a parameter so the test can pass `/dev/null` instead. Migration tests are the exception to "keep it off disk": they need real store files from every shipped model version, which is the lesson on migrations. ## Where the neighbours take over SwiftData's `ModelConfiguration` has its own in-memory option, which is the SwiftData container lesson's ground. How a test drives background contexts and merges is the lesson on managed object contexts. This setup only decides which store each test gets and which model it shares.

  • Why does a test that runs an NSBatchDeleteRequest crash on an in-memory store but pass against the app's real store?
    Batch requests run inside the SQLite store; Apple documents NSBatchDeleteRequest as available only with a SQLite persistent store. Against NSInMemoryStoreType Core Data raises an NSInternalInconsistencyException with 'Unknown command type'. Switch that test's fixture to a SQLite store at /dev/null.
  • Do two containers that both load a SQLite store at /dev/null share data?
    No. Each container that loads /dev/null gets its own empty store, so a row saved through one never appears in the next. That is what makes it a safe per-test fixture; keep everything a test needs inside one container.
  • What does the 'Multiple NSEntityDescriptions claim the NSManagedObject subclass' warning mean in a test run?
    Several loaded copies of the model map one entity to the same subclass, so Order.entity() and Order(context:) can pick an entity from the wrong model. Load the model once in a static property and pass it to every container with init(name:managedObjectModel:).

  • An in-memory store is SQLite held in RAM, so every SQLite feature works on it.
  • Each test should load the compiled model again to start clean.
  • A /dev/null URL only works with the in-memory store type.
  • NSXMLStoreType is the readable store type to use in iOS tests.
  • On an in-memory store a batch delete just reports zero rows.