2017-07-28 8 views
0

私は単純にメソッドを持っている:メインスレッドでasyncを実行するメソッドをテストするには?

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) 
} 

それdoesntの仕事、メインスレッド上で実行され...私はにupdate(with)に完了ブロックを追加しないようしたいと思いますので、検査を通る。

答えて

0

完了ブロックを使用する必要があります。非同期関数をテストするには、期待値を使用してください。

let expectation = expectation(description: "expectation") 

doStuffWithCompletion() { 
    expectation.fulfill() 
} 

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

メソッドには完了ブロックが必要です。 は、その後、あなたは

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

または完了ブロックを追加することを避けるために、あなたはセットアップが終了したときに呼び出されるメソッドを持つプロトコルを作成することができExpectationオブジェクトを使用することができます。

関連する問題