func testAscynFunction() { someAsyncFunction() } func someAsyncFunction() { let bg = DispatchQueue.global(qos: .background) bg.asyncAfter(deadline: .now() + 5) { XCTAssert(false, "Something went wrong") } }
class TestAsyncTests: XCTestCase { // 1) объявляем expectation var expectation: XCTestExpectation! func testWithExpectationExample() { //2) Инициализируем его expectation = expectation(description: "Testing Async") //3) задаем то количество раз, сколько должен исполниться метод expectation.fulfill() expectation.expectedFulfillmentCount = 5 for index in 0...5 { someAsyncFunctionWithExpectation(at: index) } //5) Ожидаем пока исполнится нужное количество expectation.fulfill() // в противном же случае по истечении 60 сек метод сам выдаст ошибку, так как не дождался waitForExpectations(timeout: 60) { (error) in if let error = error { XCTFail("WaitForExpectationsWithTimeout errored: \(error)") } } } func someAsyncFunctionWithExpectation(at index: Int) { let bg = DispatchQueue.global(qos: .background) bg.asyncAfter(deadline: .now() + 5) { [weak self ] in XCTAssert(false, "Something went wrong at index \(index)") //4) Именно его исполнение и подсчитывает expectation.expectedFulfillmentCount self?.expectation.fulfill() } } }
Source: https://habr.com/ru/post/439772/