なんとかするから、なんとかなる

エンジニア関係のことを書きます

iOS How to wait for the async procedure in XCTest

Introduction

This article shows how to wait for an async procedure like API Request or some closure.

Solution

It is easy to wait an async procedure using "expectation"

Sample Code

let request = SomeRequest()
let expect = expectation(description: "SendMyRequest")
APIClient.send(request: request) { (result) in
    switch result {
    case .success(let response):
        expect.fulfill()
    case .failure(let error):
        XCTFail("Failuer in API Client")
    }
}
waitForExpectations(timeout: 5) { (error) in
    if let error = error {
    // Some error occured like network error.
        print(error)
        XCTFail("ExpectaionTimeOut")
    } else {
    // Finished with no error.
    }
}

Detail

At first, declare the expectation with some identifier.

let expect = expectation(description: "SOME IDENTIFIER FOR THE LOG")

To expect the above valuable.

Call the fulfill method when an async procedure finished.

expect.fulfill()

At last, call the waitForExpectations(timeout:handler:) method with time out duration and completion handler.

waitForExpectations(timeout: 5) { (error) in
    // Do something if you want. If some error happened, the error value is not nil.
}