unit testing iOS function with dispatch

96 Views Asked by At

I'm working with unit testing for the first time and I'm lost with some specific cases.

Despite reading a lot I'm confused about how to test a function like this in 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
         });
    });
}

I've read about "expectations" (https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations?language=objc), but I don't know how to use them. I guess I should have to call expectation.fulfill(), but I don't know where.

1

There are 1 best solutions below

0
Paulw11 On BEST ANSWER

Since myFunction doesn't accept a completion handler in which you can call fulfill, it isn't testable.

You would need to refactor the function to accept an optional completion handler closure and to invoke it once the work is complete. You can then pass a closure when you call the function from your test in which you can fulfill the expectation.