Database Reference
In-Depth Information
1. Right-click the
Services
group under the
CampgroundManagerTests
group
and click
New File
.
2. Select
Test Case Class
. Click
Next
.
3. Name the class
CamperServiceTests
(subclass of
XCTestCase
should already
be selected) and pick
Swift
for the language.
4. Make sure the
CampgroundManagerTests
target checkbox is the only target
selected. Click
Create
.
In
CamperServiceTests.swift
, import the app and Core Data frameworks into the
test case, along with the other existing import statements:
import
CampgroundManager
import
CoreData
Add two properties to the class:
var
camperService:
CamperService
!
var
coreDataStack:
CoreDataStack
!
These properties will hold references to the
CamperService
instance to test and to
the Core Data stack. The properties are implicitly unwrapped optionals, since they'll
be initialized in
setUp
rather than in
init
.
Next, replace the implementation of
setUp
with the following:
override
func
setUp() {
super
.
setUp
()
coreDataStack = TestCoreDataStack()
camperService
=
CamperService
(
managedObjectContext:
coreDataStack
.
mainContext
!,
coreDataStack:
coreDataStack
)
}
setUp
is called before each test runs, and this is your chance to create any
resources required by all unit tests in the class. In this case, you initialize the
camperService
and
coreDataStack
properties.
It's wise to reset your data after every test so that results are repeatable. Using the
in-memory store and creating a new context in
setUp
accomplishes this reset for
you.
Notice the
CoreDataStack
instance is actually a
TestCoreDataStack
instance. The
CamperService
initialization method takes the context it needs and also an instance
of the
CoreDataStack
, since the context save methods are part of that class. You
can also use
setUp()
to insert standard test data into the context for use later.
Next, replace
tearDown
with the following implementation: