Database Reference
In-Depth Information
Core Data stack for testing
Good unit tests follow the acronym FIRST :
F ast: If your tests take too long to run, you won't bother running them.
I solated: Any test should function properly when run on its own or before or after
any other test.
R epeatable: You should get the same results every time you run the test against
the same codebase.
S elf-verifying: The test itself should report success or failure; you shouldn't have
to check the contents of a file or a console log.
T imely: There's some benefit to writing the tests after you've already written the
code, particularly if you're writing a new test to cover a new bug. Ideally, though,
the tests come first to act as a specification for the functionality you're
developing.
CampgroundManager uses Core Data to store data in a database file on disk. That
doesn't sound very I solated, since the data from one test may be written out to the
database and could affect other tests. It doesn't sound very R epeatable, either,
since data will be building up in the database file each time. You could manually
delete and recreate the database file before running each test, but that wouldn't be
very F ast.
The solution is a modified Core Data stack that uses an in-memory store instead
of an SQLite-backed store. This will be fast and provide a clean slate every time.
The CoreDataStack you've been using in most of this topic can support multiple
contexts, including a background root/parent context to which the
NSPersistentStoreCoordinator is connected. When you use CoreDataStack for a
test, you don't want it to access the SQLite database but rather an in-memory
store. Create a new class that subclasses CoreDataStack so you can change the
store:
1. Right-click Services under the CampgroundManagerTests group and click
New File .
2. Select Swift File under iOS/Source . Click Next .
3. Name the file TestCoreDataStack.swift . Make sure only the
CampgroundManagerTests target is selected.
4. Select No if prompted to add an Objective-C bridging header.
5. Click Create .
Replace the contents of the file with the following:
import CampgroundManager
import Foundation
import CoreData
 
Search WWH ::




Custom Search