Search code examples
swiftunit-testingxctestxctestexpectationxctwaiter

How to test async functions in swift using XCTWaiter and exceptions


I want to test asynchronous functions in Swift, hence as shown below, I created a XCTestExpectation and passed it on to an XCTWaiter. Now, irrespective if the expectation is fulfilled or not, I get a test ran successfully always.

Can you point out what is wrong in the code. I followed exactly a blog which was made for Swift 3, however, I am running Swift 4. Is that the issue?

func testAsyncFunction() {
        let expectation = XCTestExpectation(description: "Some description")
        vc.asyncFunction(5) { (abc: Int) -> Int in
            if (abc != 25) {
                // expectation.fulfill()
            }
            return 0
        }
        _ = XCTWaiter.wait(for: [expectation], timeout: 2.0)
    }

Solution

  • XCTWaiter.wait returns an XCTWaiter.Result which you should be observing.

    func testAsyncFunction() {
        let expectation = XCTestExpectation(description: "Some description")
        vc.asyncFunction(5) { (abc: Int) -> Int in
            if (abc != 25) {
                // expectation.fulfill()
            }
            return 0
        }
    
        let result = XCTWaiter.wait(for: [expectation], timeout: 2.0) // wait and store the result
        XCTAssertEqual(result, .timedOut) // check the result is what you expected
    }