📜 ⬆️ ⬇️

Writing Unit Tests on Swift for Verifying Asynchronous Tasks

Today I want to quickly tell you how to test asynchronous code.
Imagine the situation that you need to download data from the Internet and check whether everything is working fine, or some other task that is being performed asynchronously. And how to test it? What if you try just like regular synchronous code ?!
func testAscynFunction() { someAsyncFunction() } func someAsyncFunction() { let bg = DispatchQueue.global(qos: .background) bg.asyncAfter(deadline: .now() + 5) { XCTAssert(false, "Something went wrong") } } 


Such a test will return us a positive result, since the method will not wait for all our asynchronous tasks.

To solve this problem in tests there is one wonderful thing: XCTestExpectation
XCTestExpectation sets how many times the asynchronous method should be executed and only after all these executions the test will end and tell if there were any errors. Here is an example:

 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() } } } 


I hope someone will be useful this note.

Source: https://habr.com/ru/post/439772/