带有调度的单元测试 iOS 函数

unit testing iOS function with dispatch

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

尽管阅读了很多书,但我对如何在 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
         });
    });
}

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

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

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