Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API violation - multiple calls made to -[XCTestExpectation fulfill]

Tags:

swift

xctest

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?

like image 523
grabury Avatar asked Jan 28 '15 10:01

grabury


1 Answers

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
like image 56
Cirec Beback Avatar answered Sep 30 '22 06:09

Cirec Beback