OStack程序员社区-中国程序员成长平台

标题: ios - XCTest : Can expectationForPredicate fulfill on async variable change? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:44
标题: ios - XCTest : Can expectationForPredicate fulfill on async variable change?

我正在使用 expect(for:evaluateWith: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")
        }
   }
}



Best Answer-推荐答案


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

import Foundation

class ProductionClass : NSObject {
    var areWeDone = false

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

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






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4