我在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
处理程序块?
答案 0 :(得分:2)
您必须使用dynamic
关键字在
dynamic var testedProperty: NSString = "Before"