swiftunit-testingxctestxctestexpectationxctestcase

keyValueObservingExpectationForObject handler block not called


I have a testing case in Swift trying to wait for a property change:

    import XCTest

class AsynchronyousKVOTests: XCTestCase {

    let testedObject : TestedObjet = TestedObjet.init()

    func testKeyValueObservingExpectationForObject() {

        // 1st approach, fails:
        keyValueObservingExpectationForObject(self.testedObject, keyPath: "testedProperty") { object, changes in

            return true // Breakpoint never reached!
        }

        // 2nd approach, also fails:
        keyValueObservingExpectationForObject(self.testedObject, keyPath: "testedProperty", expectedValue: "After")

        self.testedObject.updateTestedPropertyAsynchronyously("After")
        // Expectation not fullfilled
        waitForExpectationsWithTimeout(2, handler: nil)
    }
}

class TestedObjet : NSObject {

    var testedProperty : NSString = "Before"

    func updateTestedPropertyAsynchronyously(value: NSString) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
            sleep(1)
            dispatch_sync(dispatch_get_main_queue(), {
                self.testedProperty = value
        })
        })
    }

}

Why testKeyValueObservingExpectationForObject handler block is never called?

enter image description here


Solution

  • You have to enable key value observation in Swift with the dynamic keyword:

    dynamic var testedProperty: NSString = "Before"