Database Reference
In-Depth Information
func testReserveCampSiteNegativeNumberOfDays() {
let camper = camperService . addCamper ( "Johnny Appleseed" ,
phoneNumber: "408-555-1234" )!
let campSite = campSiteService !. addCampSite ( 15 ,
electricity: false , water: false )
let result = reservationService !. reserveCampSite (campSite,
camper: camper, date: NSDate (), numberOfNights: - 1 )
XCTAssertNotNil (result.reservation,
"Reservation should not be nil" )
XCTAssertNotNil (result.error, "An error should be present" )
XCTAssertTrue (result.error?. userInfo ?[ "Problem" ] as ? NSString
== "Invalid number of days" ,
"Error problem should be present" )
XCTAssertTrue (result.reservation?. status == "Invalid" ,
"Status should be Invalid" )
}
Run the unit test, and you'll notice the test fails. Apparently whoever wrote
ReservationService didn't think to check for this! It's a good thing you caught it
here in the test rather than a real user out in the wild - maybe booking a negative
number of nights would go as far as to issue a refund!
Tests are a great place for probing your system like this and finding holes in the
behavior. As an added benefit, the test provides something like a specification too -
the tests is saying you're still expecting a valid non-nil result, but with the error
condition set.
Open ReservationService.swift and add the check for numberOfNights to
reserveCampSite . Replace the line reservation.status = "Reserved" with the
following:
if numberOfNights <= 0 {
reservation. status = "Invalid"
registrationError = NSError (domain: "CampingManager" ,
code: 5 , userInfo: [ "Problem" : "Invalid number of days" ])
} else {
reservation. status = "Reserved"
}
Now rerun the tests and see that the negative number of days test passes. You can
see how the process continues with refactoring when you want to add additional
functionality or validation rules.
Whether you know the details of the code you're testing or if you're treating it like a
black box, you can write these kinds of tests against the API to see if behaves as
Search WWH ::




Custom Search