【问题标题】:unit testing iOS function with dispatch使用 dispatch 对 iOS 功能进行单元测试
【发布时间】:2020-06-17 13:24:36
【问题描述】:

我是第一次进行单元测试,但我对一些特定情况感到迷茫。

尽管阅读了很多书,但我对如何在 iOS 中测试这样的功能感到困惑:

func myFunction() {

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
          // Tasks to do in background
            dispatch_async(dispatch_get_main_queue(), ^(void){
            // Get the results
            // Update UI
         });
    });
}

我读过“期望”(https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations?language=objc),但我不知道如何使用它们。我想我应该打电话给 expect.fulfill(),但我不知道在哪里。

【问题讨论】:

    标签: ios unit-testing dispatch-async expectations


    【解决方案1】:

    由于myFunction 不接受可以调用fulfill 的完成处理程序,因此它不可测试。

    您需要重构函数以接受可选的完成处理程序闭包,并在工作完成后调用它。然后,当您从测试中调用函数时,您可以传递一个闭包,您可以在其中 fulfill 期望。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-25
      • 2017-04-14
      • 1970-01-01
      • 2022-10-20
      • 2018-06-27
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多