XCTest 异步函数 Swift

XCTest Async Function Swift

我是 XCTest 的新手,我已经在模型、视图、控制器中构建了我的代码

所以控制器将从模型中获取数据,一旦获取数据,控制器将更新视图。 所以我有我的控制器并查看如下

控制器:

func loadData() {
    Model.provideData { response in
        if response != nil {
            view.refresh()
        }
    }
}

查看:

func refresh() {
    isViewLoaded = true
}

这是我的 XCTest

func testLoadData() {
    let sut = Controller()
    let mockView = View()
    mockView.setController(controller: sut)
    controller.loadData()
    /** HERE is the problem, because it is a ASYNC call, i need to wait for the flag is set **/
    XCTAssertTrue(mockView.isViewLoaded, "isViewLoaded equals to true")
}

我知道我可以

let expectation = expectation(description: "wait for isViewLoaded set to true")

但是我应该把 expectation.fulfill() 放在哪里?

waitForExpectation(timeout: 5, handler: nil)

感谢任何帮助。谢谢

您需要 loadData 有一个完成处理程序,因此能够在异步函数完成时通知其调用者。

func loadData(completion: @escaping () -> Void) {
    Model.provideData { response in
        if response != nil {
            view.refresh()
        }
        completion()
    }
}

然后在您的测试中,在 loadDatacompletion 中执行 expectation.fulfill

func testLoadData() {
    let expectation = expectation(description: "wait for isViewLoaded set to true")
    let sut = Controller()
    let mockView = View()
    mockView.setController(controller: sut)
    controller.loadData {
        expectation.fulfill()
    }
    waitForExpectation(timeout: 5, handler: nil)
    XCTAssertTrue(mockView.isViewLoaded, "isViewLoaded equals to true")
}