Database Reference
In-Depth Information
Here's a breakdown of the code:
1. You create a text expectation linked to a notification. In this case, the
expectation is linked to
NSManagedObjectContextDidSaveNotification
from the root
context of the Core Data stack. The handler for the notification is simpleāit
returns
true
since all you care about is that the notification is fired.
2. You add the camper, exactly the same as before.
3. The test waits up to two seconds for the expectation. If there are errors or the
timeout passes, the
error
parameter for the handler block will contain a value.
It's important to keep UI-blocking operations such as Core Data saving off the main
thread so your app stays responsive. Test expectations are invaluable to make sure
these asynchronous operations are covered by unit tests.
You've added tests for existing features in the app; now it's time to add some
features yourself. [TODO: Sentence fragment?] Along with the tests too, of course.
Or for even more fun: perhaps write the tests first?
Tests first
An important function of CampgroundManager its ability to reserve sites for
campers. Before it can accept reservations, the system has to know about all of the
campsites at the campground. I created
CampSiteService
to help with adding,
deleting and finding campsites.
Open
CampSiteService
, and you'll notice the only method I've implemented is
addCampSite
. There are no unit tests for this method, so start by creating a test
case for the service:
1. Right-click
Services
under the
CampgroundManagerTests
group and click
New File
.
2. Select
Test Case Class
. Click
Next
.
3. Name the class
CampSiteServiceTests
(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
.
Replace the contents of the file with the following:
import
UIKit
import
XCTest
import
CampgroundManager
import
CoreData
class
CampSiteServiceTests:
XCTestCase
{
var
campSiteService:
CampSiteService
!
var
coreDataStack:
CoreDataStack
!