0

我对 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)

任何帮助表示赞赏。谢谢

4

1 回答 1

2

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

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

然后在你的测试中,expectation.fulfillcompletionof 中做loadData

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")
}
于 2020-08-04T11:30:01.793 回答