Writing Unit Tests on Swift for Verifying Asynchronous Tasks

  • Tutorial
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 ?!

functestAscynFunction() {
        someAsyncFunction()
    }
    funcsomeAsyncFunction() {
        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 will tell if there were any errors. Here is an example:

classTestAsyncTests: XCTestCase{
// 1) объявляем  expectationvar expectation: XCTestExpectation!functestWithExpectationExample() {
//2) Инициализируем его 
        expectation = expectation(description: "Testing Async")
//3) задаем то количество раз, сколько должен исполниться метод  expectation.fulfill()
        expectation.expectedFulfillmentCount = 5for index in0...5 {
            someAsyncFunctionWithExpectation(at: index)
        }
//5) Ожидаем пока исполнится нужное количество expectation.fulfill()// в противном же случае по истечении 60 сек метод сам выдаст ошибку, так как не дождался
        waitForExpectations(timeout: 60) { (error) iniflet error = error {
                XCTFail("WaitForExpectationsWithTimeout errored: \(error)")
            }
        }
    }
    funcsomeAsyncFunctionWithExpectation(at index: Int) {
        let bg = DispatchQueue.global(qos: .background)
        bg.asyncAfter(deadline: .now() + 5) { [weakself ] inXCTAssert(false, "Something went wrong at index \(index)")
//4) Именно его исполнение и подсчитывает expectation.expectedFulfillmentCountself?.expectation.fulfill()
        }
    }
}

I hope someone will be useful this note.

Also popular now: