티스토리 뷰

두 가지 방법이 있는데, 첫 번째는 swift 에서 제공하는 await, async 를 사용한다.

아래의 예시를 보면 함수에 async 로 작성하고 함수에 await로 작성하였다.

 

func testDownloadWebDataWithConcurrency() async throws {
    // Create a URL for a webpage to download.
    let url = URL(string: "https://apple.com")!
    
    // Use an asynchronous function to download the webpage.
    let dataAndResponse: (data: Data, response: URLResponse) = try await URLSession.shared.data(from: url, delegate: nil)
    
    // Assert that the actual response matches the expected response.
    let httpResponse = try XCTUnwrap(dataAndResponse.response as? HTTPURLResponse, "Expected an HTTPURLResponse.")
    XCTAssertEqual(httpResponse.statusCode, 200, "Expected a 200 OK response.")
}

 

두 번째 방법은 Expectation 을 사용하는 것 이다.

1) XCTestExpectation 을 만들고, 2) wait 함수로 timeout을 지정하고 3) 만족하는 조건에서 expectation.fulfill() 함수를 실행 한다.

 

// 1. XCTestExpectation 을 만든다.
let expectation = XCTestExpectation(description: "Open a file asynchronously.")

let fileManager = ExampleFileManager()

// Perform the asynchronous task.
fileManager.openFileAsync(with: "exampleFilename") { file, error in

    // Assert that the asynchronous task worked.
    XCTAssertNotNil(file, "Expected to load a file.")

    // Assert that no errors occurred opening the file asynchronously.
    XCTAssertNil(error, "Expected no errors loading a file.")
    
    // 만족 조건을 fulfill로 작성한다.
    expectation.fulfill()
}


// 2. 타임 아웃을 설정한다.
wait(for: [expectation], timeout: 10.0)

 

참고

https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함