search
LoginSignup
7

More than 3 years have passed since last update.

posted at

updated at

XCTestで「待つ」ためのサンプルコード集

任意の時間まで待つ

任意のタイミングでexpectation.fulfill()する。

    let expectation = XCTestExpectation(description: "view hidden")
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        XCTAssertEqual(view.isHidden, true)
        expectation.fulfill()
    }
    XCTWaiter().wait(for: [expectation], timeout: 10)

NSPredicateを使って待つ

    let predicate = NSPredicate(format: "isHidden == true")
    let expectation = XCTNSPredicateExpectation(predicate: predicate, object: view)
    let result = XCTWaiter().wait(for: [expectation], timeout: 10)
    XCTAssertEqual(result, .completed)

KVOを使って待つ

    let expectation = XCTKVOExpectation(keyPath: "isHidden", object: view, expectedValue: true)
    let result = XCTWaiter().wait(for: [expectation], timeout: 10)
    XCTAssertEqual(result, .completed)

Notificationを待つ

    let expectation = XCTNSNotificationExpectation(name: notificationName)
    let result = XCTWaiter().wait(for: [expectation], timeout: 10)
    XCTAssertEqual(result, .completed)

環境

Swift 5
Xcode 10.2

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
7