繁体   English   中英

XCTest 异步 Function Swift

[英]XCTest Async Function Swift

我对 XCTest 很陌生,我在 Model 中构建了我的代码,查看,Controller

所以 controller 将从 Model 获取数据,一旦获取数据,Controller 将更新视图。 所以我有我的 Controller 并查看如下

Controller:

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有一个完成处理程序,因此能够在异步 function 完成时通知其调用者。

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

然后在您的测试中,在completion loadData时执行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")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM