Verify that asynchronous operations behave as expected.
Asynchronous operations are operations that do not execute directly within the current flow of code. This might be because they run on a different thread, in a delegate method, or in a callback.
To test that asynchronous operations behave as expected, you create one or more expectations within your test, and then fulfill those expectations when the asynchronous operation completes successfully. Your test method waits until all expectations are fulfilled or a specified timeout expires.
Listing 1 creates a new instance of
XCTest. Then, it uses
data method to create a background data task that downloads the apple.com home page on a background thread. After starting the data task, the main thread waits for the expectation to be fulfilled, with a timeout of ten seconds.
When the data task completes, its completion handler verifies that the downloaded data is non-nil, and fulfills the expectation by calling its
fulfill method to indicate that the background task completed successfully.
The fulfillment of the expectation on the background thread provides a point of synchronization to indicate that the background task is complete. As long as the background task fulfills the expectation within the ten second timeout, this test method will pass.
There are two ways for the test to fail:
The data returned to the completion handler is
XCTAssertto trigger a test failure.
Not Nil(_: _: file: line:)
The data task does not call its completion handler before the ten second timeout expires, perhaps because of a slow network connection or other data retrieval problem. As a result, the expectation is not fulfilled before the wait timeout expires, triggering a test failure.