Asynchronous Tests and Expectation

Groot·2022년 8월 24일
0

TIL

목록 보기
38/148
post-thumbnail

TIL

🌱 난 오늘 무엇을 공부했을까?

📌 Asynchronous Tests and Expectations 공식문서 정리

  • 비동기 코드가 예상대로 작동하는지 확인합니다.

📍 Overview

  • 비동기 코드는 현재 코드 흐름 내에서 직접 실행되지 않습니다.
  • 이는 코드가 다른 스레드나 디스패치 큐, 대리자 메서드 또는 콜백에서 실행되거나 비동기로 표시된 Swift 함수이기 때문일 수 있습니다.
  • XCTest는 비동기 코드를 테스트하기 위한 두 가지 접근 방식을 제공합니다.
  • async를 사용하고 동시성을 기다리는 Swift 코드의 경우 테스트 메서드를 async 또는 async throws로 표시하여 비동기식으로 테스트합니다.
  • 다른 유형의 비동기 코드의 경우 테스트 내에서 XCTest가 handle waiting을 하는데 사용하는 개체인 하나 이상의 expectations를 생성합니다.
  • 그런 다음 비동기 코드 실행이 완료되면 XCTest에 대기를 중지하도록 지시할 때 이러한 expectations를 fulfill합니다.
  • 테스트 방법은 모든 expectations가 fulfill되거나 지정된 시간 초과가 만료될 때까지 기다립니다.

📍 Build Asynchronous Tests with Swift Concurrency

  • async를 사용하고 동시성을 기다리는 Swift 코드를 테스트하려면 테스트 메서드를 async 또는 async throws로 표시합니다.
  • XCTest는 비동기 호출이 완료될 때까지 테스트가 대기하도록 테스트 메서드를 비동기적으로 실행합니다.
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.")
}
  • 비동기 작업이 완료되면 assertions을 수행하여 작업의 실제 결과가 예상 결과를 충족하는지 확인합니다.
  • 테스트에 오류가 발생하면 XCTest는 테스트 실패를 기록합니다.

    테스트 코드가 Main Actor에서 실행되어야 하는 경우 테스트 메서드 또는 클래스에 @MainActor를 지정합니다. 액터를 지정하지 않으면 테스트 메서드가 임의의 액터에서 실행됩니다.

📍 Build Asynchronous Tests with Expectations

  • Swift async를 사용할 수 없는 경우 Expectations을 사용하여 비동기 코드를 테스트하십시오.
  • 예를 들어 사용 가능한 Swift 비동기 대안이 없거나 비동기 코드가 다음에서 실행될 때 Expectations을 사용하세요.
    • Objective-C
    • An asynchronous block in a dispatch queue
    • A delegate method
    • An asynchronous callback, closure, or completion block
    • A Future or Promise in Swift Combine
    • A situation where it needs to complete within a specific amount of time
  • 테스트 메서드에서 비동기 작업을 수행하기 전에 작업 설명과 함께 XCTestExpectation의 인스턴스를 만듭니다.
// Create an expectation for an asynchronous task.
let expectation = XCTestExpectation(description: "Open a file asynchronously.")
  • 비동기 작업을 시작한 다음 지정한 시간 내에 예상이 완료될 때까지 기다리도록 테스트에 지시합니다.
let fileManager = ExampleFileManager()

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

// Wait for the expectation to fulfill or time out.
wait(for: [expectation], timeout: 10.0)
  • 비동기 작업이 반환되면(예: 콜백에서) assertions을 수행하여 작업의 실제 결과가 예상 결과를 충족하는지 확인합니다.
  • 작업이 완료되면 대기를 중지하고 다음 테스트를 진행할 수 있음을 테스트에 나타내기 위해 fulfill() 메서드를 호출합니다.
  • wait 문의 timeout가 만료되기 전에 테스트가 fulfill() 메서드를 실행하지 않으면 XCTest는 테스트 실패를 기록합니다.
    Asynchronous Tests and Expectations공식문서
profile
I Am Groot

0개의 댓글