Async XCTest Assertion Helpers

SwiftAsyncAssert by Angu (@angu@techhub.social):

Instead of writing

import XCTest

func test_should_succeed() async {
    do {
        let isTrue = try await shouldSucceed()
        XCTAssertTrue(isTrue)
    } catch {
        XCFail("Should not throw an error")
    }
}

conveniently write

import SwiftAsyncAssert

func test_should_succeed() async {
    await AsyncAssertTrue(try await shouldSucceed())
}

func test_should_throwError() async {
    await AsyncAssertThrowsError(try await shouldFail())
}

Less code for your convenience when testing!

I ran into this, too, recently and wondered how everyone’s dealing with this. Because this is so annoying, I expected more outcries on the interwebs every day.

Maybe nobody is writing tests?

Either way: These helpers look very nice, and I’ll try them for sure. Should be part of the XCTest libray in my opinion. I seriously wonder why there’s no async XCTest assertion functions for this already.

If you’re just running into this for main actor isolation: One workaround that got suggested to me is to annotate the XCTestCase subclass itself with @MainActor to circumvent having to await isolated calls everywhere. (That doesn’t help for non-main actor-isolated calls, obviously.)