2015年2月21日土曜日

Unit testで非同期処理のWaitをする

XcodeでiOS開発の勉強をはじめました。
いきなりですが、UnitTestネタです。テストしないもの、エンジニアにあらずです。

参考:Writing Test Classes and Methods

waitForExpectationsWithTimeoutで非同期処理の待ち状態を指定

標準テストフレームワークのXCTestExpectationとXCTestCase.waitForExpectationsWithTimeoutを組み合わせて実装します。
手順は次のようになります。

  1. XCTestCase.expectationWithDescriptionをコールして、XCTestExpectationを取得 
  2. XCTestCase.waitForExpectationsWithTimeoutで、waitを指定 
  3. 非同期処理終了のタイミングで、XCTestExpectation.fulfill()。もし、waitForExpectationsWithTimeoutで指定した時間内にコールしなければfailとなる

サンプルプログラムです。
1
2
3
4
5
6
7
8
9
10
11
func testPerformAsyncRequest(){
    // XCTestExpectationの取得
    let expectation = self.expectationWithDescription("client key")
 
    // 非同期処理のコールバック処理完了後、expectation.fulfill()をコール
    expectation.fulfill()
     
    //waitの時間指定
    self.waitForExpectationsWithTimeout(5, handler: nil)
     
}

0 件のコメント:

コメントを投稿