未调用 keyValueObservingExpectationForObject 处理程序块

keyValueObservingExpectationForObject handler block not called

我在 Swift 中有一个测试用例正在尝试等待 属性 更改:

    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
        })
        })
    }

}

为什么从不调用 testKeyValueObservingExpectationForObject 处理程序块?

您必须使用 dynamic 关键字在 Swift 中启用键值观察:

dynamic var testedProperty: NSString = "Before"