I'm writing one of my first integration tests in Swift.
I'm trying to check if an image exists at a particular url.
I want to perform a head request and check the response's status code.
I keep getting the error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'API violation - multiple calls made to -[XCTestExpectation fulfill].
I've tried making the expectation a weak variable.
I have the following code/test:
func testAndroidImagesExist() {
 weak var expectation: XCTestExpectation?
 expectation =  expectationForNotification(kBaoNotification_ManifestImportCompleted, object: nil) { (notification: NSNotification!) -> Bool in
 let userInfo: NSDictionary = notification.userInfo!
 var titles = userInfo.valueForKey("titles") as? NSArray
 titles?.enumerateObjectsUsingBlock({ (t: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
  let title = t as NSDictionary
  let titleLabel = title.valueForKey("title") as String
  let parameters = title.valueForKey("parameters") as NSDictionary
  let androidImageUrl = parameters.valueForKey("android_logo_url") as String
  var androidRequest = NSMutableURLRequest(URL: NSURL(string: androidImageUrl)!)
  androidRequest.HTTPMethod = "HEAD"
  var androidResponse: NSURLResponse?
  var androidData = NSURLConnection.sendSynchronousRequest(androidRequest, returningResponse: &androidResponse, error: nil)
  var androidHttpResponse = androidResponse as? NSHTTPURLResponse
  if androidHttpResponse != nil {
   if androidHttpResponse!.statusCode == 404 {
    XCTFail("Android image not found for title \(titleLabel)")
   }
  } else {
   XCTFail("No response from android image for title \(titleLabel)")
  }
 })
 expectation?.fulfill()
 return true
}
 waitForExpectationsWithTimeout(10, handler: { (error: NSError!) -> Void in
  if (error != nil) {
   XCTFail("Timeout error: \(error)")
  }
 }) 
}
Any ideas?
I suggest best handing of a multiple occurring expectation is to set your expectation variable to nil after the fulfill. Then, subsequent calls will be ignored.
Objective-C:
// Fulfill and remove. Subsequent messages to nil are ignored.
[multiEx fulfill];
multiEx = nil;`
Swift:
// Fulfill and remove. Optional chaining ends execution on nil.
var multiEx:XCTestExpectation? = expectationWithDescription("multiEx")
...
multiEx?.fulfill() 
multiEx = nil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With