Skip to content

Instantly share code, notes, and snippets.

@huguesbr
Last active April 8, 2016 09:29
Simple extension on XCTestExpectation to allow to specify an expectation count. see following test for exemple
//
// XCTestExpectationExtensions.swift
//
// Created by Hugues Bernet-Rollande on 7/4/16.
//
import XCTest
extension XCTestExpectation {
private class IntWrapper {
let value :Int!
init?(value:Int?) {
self.value = value
if (value == nil) {
return nil
}
}
}
private struct AssociatedKey {
static var expectationCountKey = ""
}
var expectationCount:Int? {
get {
return objc_getAssociatedObject(self, &AssociatedKey.expectationCountKey) as? Int
}
set {
objc_setAssociatedObject(self, &AssociatedKey.expectationCountKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
func decrementalFulfill() {
guard let expectationCount = self.expectationCount else {
fulfill()
return
}
self.expectationCount = expectationCount - 1
if self.expectationCount <= 0 {
fulfill()
}
}
}
class XCTestExpectationExtensionsTests: XCTestCase {
func testMultiple() {
weak var e = expectationWithDescription("call twice")
e?.expectationCount = 2
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
e?.decrementalFulfill()
e?.decrementalFulfill()
})
waitForExpectationsWithTimeout(1.0, handler: nil)
}
func testNil() {
weak var e = expectationWithDescription("call once")
e?.expectationCount = 2
e?.expectationCount = nil
XCTAssertNil(e?.expectationCount)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
e?.decrementalFulfill()
})
waitForExpectationsWithTimeout(1.0, handler: nil)
}
}
@huguesbr
Copy link
Author

huguesbr commented Apr 8, 2016

Updating to use weak reference to expectation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment