objective-c - XCTKVOExpectation 在 objective-c 中的使用示例

标签 objective-c xctest

我想在 objective-c 中编写单元测试。为此,我只需要在观察到的对象的键值变为预期值时运行我的测试。

苹果文档没有详细解释实现。任何示例代码都会有很大帮助。

最佳答案

这是一个 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)

关于objective-c - XCTKVOExpectation 在 objective-c 中的使用示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172971/

相关文章:

objective-c - 将图像写入 cocoa 应用程序中的文件

objective-c - 使用 Nibs 进行国际化。这真的是个好主意吗?

iphone - isMemberOfClass Terminology - 为什么这样命名?

ios - 测试类包返回 Xcode 10 中的主包,而不是单元测试包

ios - Unwind Segue 在 iOS 8 中不起作用

ios - 将字符串分配给 UILabel 时的延迟

ios - 如何对 drawRect 的自定义实现进行单元测试

ios - 使用 XCTest 测试 iOS 应用程序时检查 XCUIElement 在屏幕上的位置

ios - XCTest:点击 navigationItem 返回按钮