菜鸟教程小白 发表于 2022-12-11 20:44:18

ios - XCTest : Can expectationForPredicate fulfill on async variable change?


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

<p>我不想通过添加人工完成 block 或通知来弄乱我的生产代码。 </p>

<pre><code>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: &#34;areWeDone = %d&#34;, true)
      let exp = expectation(for: predicate, evaluatedWith: productionClass, handler: nil)

      productionClass.doSomeStuff()

      let result = XCTWaiter.wait(for: , timeout: 3)
      if result != XCTWaiter.Result.completed {
            XCTAssert(false, &#34;areWeDone changed but test timeout&#34;)
      }
   }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>解决方案非常简单 - 只需确保“ProductionClass”类继承自 NSObject 并且您的测试将按预期工作:</p>

<pre><code>import Foundation

class ProductionClass : NSObject {
    var areWeDone = false

    func doSomeStuff() {
      DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            self.areWeDone = true
      }
    }
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - XCTest : Can expectationForPredicate fulfill on async variable change?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/53001940/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/53001940/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - XCTest : Can expectationForPredicate fulfill on async variable change?