gpt4 book ai didi

ios - XC测试 : Can expectationForPredicate fulfill on async variable change?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:01 25 4
gpt4 key购买 nike

我正在使用 expectation(for:evaluatedWith:handler:) 来观察生产代码中的变量是否发生变化,但它从未实现 - 为什么?

我不想通过添加人为的完成 block 或通知来弄乱我的生产代码。

class ProductionClass {
var areWeDone = false

func doSomeStuff() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
self.areWeDone = true
}
}
}

class Test: XCTestCase {
override func setUp() { }
override func tearDown() { }

func testDoSomeStuff() {
let productionClass = ProductionClass()
let predicate = NSPredicate(format: "areWeDone = %d", true)
let exp = expectation(for: predicate, evaluatedWith: productionClass, handler: nil)

productionClass.doSomeStuff()

let result = XCTWaiter.wait(for: [exp], timeout: 3)
if result != XCTWaiter.Result.completed {
XCTAssert(false, "areWeDone changed but test timeout")
}
}
}

最佳答案

解决方案非常简单 - 只需确保类“ProductionClass”继承自 NSObject 并且您的测试将按预期工作:

import Foundation

class ProductionClass : NSObject {
var areWeDone = false

func doSomeStuff() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
self.areWeDone = true
}
}
}

关于ios - XC测试 : Can expectationForPredicate fulfill on async variable change?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53001940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com