Last active
April 8, 2016 09:29
-
-
Save huguesbr/7d110bffd043e4d11f2886693c680b06 to your computer and use it in GitHub Desktop.
Simple extension on XCTestExpectation to allow to specify an expectation count. see following test for exemple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updating to use weak reference to expectation