如何测试在主线程上运行异步的方法?

时间:2017-07-28 08:29:24

标签: ios swift unit-testing

我只是有一个方法:

func update(with process: PresentableProcess) {
    presentableProcess = process
    if isViewLoaded {
        DispatchQueue.main.async { [weak self] in
            //do sth on the main thread
        }
    }
}

它的测试:

func testPreferredContentSizeWhenTitleExist() {
    let process = PresentableProcess(title: "title")
    sut.update(with: process)

    XCTAssertEqualWithAccuracy(sut.preferredContentSize, 95, accuracy: 10)
}

它不起作用,因为在主线程上运行...我想避免在update(with)中添加完成块来传递测试。

2 个答案:

答案 0 :(得分:0)

我担心你需要使用完成块。测试异步函数使用期望

let expectation = expectation(description: "expectation")

doStuffWithCompletion() {
    expectation.fulfill()
}

waitForExpectations(timeout: 10) { error in
    //
}

答案 1 :(得分:0)

您的方法必须有完成块。 然后,您可以使用let urlExpectation = expectation(description: "GET \(url)") let process = PresentableProcess(title: "title") sut.update(with: process) { XCTAssertEqualWithAccuracy(sut.preferredContentSize, 95, accuracy: 10) urlExpectation.fulfill() } 对象

//view 
<button ng-click="toggleCustom()">Custom</button>
        <span ng-hide="custom">From:
            <input type="text" id="from" />
        </span>
        <span ng-hide="custom">To:
            <input type="text" id="to" />
        </span>
        <span ng-show="custom"></span>

//controller
$scope.custom = true;
        $scope.toggleCustom = function() {
            $scope.custom = $scope.custom === false ? true: false;
        };

或者为了避免添加完成块,您可以使用设置结束时调用的方法创建协议。