我想在目标c中编写单元测试。为此,仅在观察对象的键值变为期望值时才需要运行测试。
Apple文档没有详细解释该实现。任何示例代码都会有很大帮助。
答案 0 :(得分:0)
这是Swift中的一个示例实现,我希望这可以向您展示如何使用KVO期望值。
传递给期望值的处理程序将两个对象作为输入(您正在观察的对象和变化字典)。如果您对值已按预期更改感到满意,则应返回true
,如果未满足期望,则应返回false
。
class Person: NSObject {
@objc dynamic var name: String
init(name: String) {
self.name = name
}
func changeName(to newName: String) {
name = newName
}
}
class Tests: XCTestCase {
func testNameValueChangedWhenChangeNameCalled() {
let person = Person(name: "Alice")
let newName = "Bob"
keyValueObservingExpectation(for: person, keyPath: "name", handler: { (observedObject, change) in
// `observedObject` is of type `Any` so it needs to be cast as the correct type before proceeding
guard let observedObject = observedObject as? Person else {
// Don't fulfill the expectation
return false
}
// Check the current name is the name we expect
return observedObject.name == newName
})
person.changeName(to: newName)
waitForExpectations(timeout: 1, handler: nil)
}
}
您还可以直接初始化XCTKVOExpectation
并使用XCTWaiter
来更精细地处理结果。
let person = Person(name: "Alice")
let newName = "Bob"
let expectation = XCTKVOExpectation(keyPath: "name", object: person)
expectation.handler = { (observedObject, change) in
guard let observedObject = observedObject as? Person else {
return false
}
return observedObject.name == newName
}
person.changeName(to: newName)
let result = XCTWaiter().wait(for: [expectation], timeout: 1)
XCTAssertEqual(result, .completed)
答案 1 :(得分:0)
以下是如何使用keyValueObservingExpectation的示例:
let testClass = MyViewController()
let expectation = keyValueObservingExpectation(for: testClass, keyPath: #keyPath(MyViewController.urlString))
wait(for: [expectation], timeout: 10)
要使用它,必须使用#keyPath(MyViewController.urlString)指定keyPath。在该代码中,正在观察urlString的值。
这是此https://www.rockhoppertech.com/blog/kvo-quick-spec-unit-tests/
的另一个示例