LoginSignup
15
7

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-08-29

任意の時間まで待つ

任意のタイミングで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

参考

15
7
1

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
  3. You can use dark theme
What you can do with signing up
15
7