Logo for tanaschita.com

How to unit test async/await functions in Swift

Learn how to write unit tests for async/await functions.

20 Jul 2021 · 2 min read

With async/await, unit testing asynchronous code in Swift got easier and shorter compared to testing asynchronous code with completion handlers.

We don't need to setup and handle an XCTestExpectation anymore. All we have to do is to mark the test function with async and call await on the async call.

import XCTest
class FibonacciSequenceTests: XCTestCase {
func testFibonacciSequence() async {
let result = await fibonacciSequence(count: 7)
XCTAssertEqual([0, 1, 1, 2, 3, 5, 8], result)
}
}

Or, if the method can throw an error:

func testFibonacciSequence() async {
let result = try? await fibonacciSequence(count: 7)
XCTAssertNotNil(result)
XCTAssertEqual([0, 1, 1, 2, 3, 5, 8], result)
}

Related tags

Written by

Articles with related topics

Latest articles and tips