如何使用expectationForNotification

时间:2015-11-11 01:14:50

标签: ios swift xctest xctestexpectation

我已经尝试了所有的东西,但我能成功测试的唯一方法就是在测试功能中实际发送通知,这有点挫败了目的。

我有一个按钮。当我点击按钮时,它会发送通知。如何使用expectationForNotification查看此通知是否已发送?

func testExample() {
    let app = XCUIApplication()
    let button = app.buttons["Button"]
    let expectation = expectationForNotification("TEST_NOTE", object: nil) {
        (notification: NSNotification!) -> Bool in

        print("SUCCESS")
        return true
    }

    button.tap()

    waitForExpectationsWithTimeout(5, handler: nil)
}

1 个答案:

答案 0 :(得分:2)

在我看来,你必须满足期望......

func testExample() 
{
     let app = XCUIApplication()
     let button = app.buttons["Button"]

     let expectation = expectationWithDescription("waiting for the tap")

      expectationForNotification("TEST_NOTE", object: nil)
      {
        notification in
        expectation.fulfill()
        return true
      }

      button.tap()

      waitForExpectationsWithTimeout(30)
      {
            error in 
            if let e = error
            {
                XCTFail("\(e.debugDescription)")
            }
       } 
}