未调用keyValueObservingExpectationForObject处理程序块

时间:2016-03-10 09:38:04

标签: swift unit-testing xctest xctestexpectation xctestcase

我在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处理程序块?

enter image description here

1 个答案:

答案 0 :(得分:2)

您必须使用dynamic关键字在

中启用Swift中的键值观察
dynamic var testedProperty: NSString = "Before"