iOS/Test

테스트 응용 - 비 동기 실행

@서비 2022. 8. 9. 19:28

두 가지 방법이 있는데, 첫 번째는 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