2016-12-14 45 views
6

我正在運行UI測試,我需要使用waitForExpectations API測試異步函數。使用waitForExpectations時發生API違例

我得到這個錯誤:

"NSInternalInconsistencyException", "API violation - call made to wait without any expectations having been set."

我真的不明白,因爲我已經正確地創建了期望。

此外,似乎有一個文檔錯誤:根據文檔的API是expectation(description:)但編譯器不會接受,而是我需要使用XCTestExpectation()創建一個。

func testExample() { 
    XCTAssertTrue(state == .STATE_NOT_READY) 
    let exp1 = XCTestExpectation() 

    let queue = DispatchQueue(label: "net.tech4freedom.AppTest") 
    let delay: DispatchTimeInterval = .seconds((2)) 
    queue.asyncAfter(deadline: .now() + delay) { 
     XCTAssertTrue(true) 
     exp1.fulfill() 
    } 

    self.waitForExpectations(timeout: 4){ [weak self] error in 
     print("X: async expectation") 
     XCTAssertTrue(true) 
    } 
    self.waitForExpectations(timeout: 10.0, handler: nil) 
} 
+0

你什麼錯誤,當你使用'self.expectation(說明:)'?因爲這是做這件事的正確方法,否則你的測試班不知道你創造了你的期望。 – Losiowaty

+0

如果我嘗試用描述參數(let exp1 = XCTestExpectation(description:「ss2」))創建期望值,那麼我會得到「參數傳遞給不帶參數的調用」 – onthemoon

回答

8

好的,你的錯誤是你試圖直接實例化期望值。該文檔說清楚

Use the following XCTestCase methods to create XCTestExpectation instances:
- expectation(description:)

這意味着,你應該建立這樣的預期:

func testMethod() { 
    let exp = self.expectation(description: "myExpectation") 
    // your test code 
} 
+1

您也可以調用API'wait :[XCTestExpectation],超時秒數:TimeInterval)',如果它們來自某些測試存根類,則傳入期望值。 –

相關問題