2017-07-28 77 views
0

我只是有一個方法:如何測試在主線程上運行異步的方法?

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)將完成塊考試及格。

回答

0

恐怕您需要使用完成塊。要測試異步功能使用期望

let expectation = expectation(description: "expectation") 

doStuffWithCompletion() { 
    expectation.fulfill() 
} 

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

您的方法必須有一個完成塊。 然後可以使用一個Expectation對象

let urlExpectation = expectation(description: "GET \(url)") 
let process = PresentableProcess(title: "title") 
sut.update(with: process) { 
    XCTAssertEqualWithAccuracy(sut.preferredContentSize, 95, accuracy: 10) 
    urlExpectation.fulfill() 
} 

或避免加入完成塊,則可以創建具有當安裝結束調用的方法的協議。

相關問題