How to test async functions in swift using XCTWaiter and exceptions

寵の児 提交于 2019-12-11 17:35:02

问题


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

回答1:


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
}


来源:https://stackoverflow.com/questions/50000764/how-to-test-async-functions-in-swift-using-xctwaiter-and-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!