单元测试异步等待失败:超时超过Swift

时间:2019-01-17 10:58:54

标签: swift unit-testing

我正在尝试对我的应用程序进行单元测试,并且大多数测试失败,原因是异步等待失败:超过了30秒的超时,并没有实现期望:“本地代码”。

我不知道为什么它会失败,但这是下面的代码

class HomeTest: XCTestCase {

    override func setUp() {
    }

    override func tearDown() {
    }

    func testHome() {
        let expec = expectation(description: "Home Code")
        let presenter =  HomePresenter(view: HomeTestVC(expectation: expec), source: Repository.instance)
        presenter.start()
        wait(for: [expec], timeout: 30)
    }

    func testPerformanceExample() {
        self.measure {
        }
    }

}


class HomeTestVC: HomeContract.View {
    func showRatingForLastTrip(_ trip: Trip) {}

    func setProgress(enabled: Bool) {}

    func didFail(message: String) {}

    func didShowError(error: Error) {}

    func didShowStatusCode(code: Int?) {
        XCTAssertGreaterThan(200, code ?? 0)
        self.expec.fulfill()
    }

    var expec: XCTestExpectation
    init(expectation: XCTestExpectation) {
        self.expec = expectation
    }
} 

它会弹出模拟器,但仅停留在第一个屏幕上。我不知道为什么。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

您没有实现您的期望

func testExample() {
    let expec = expectation(description: "Home Code")
    someAsyncTask() { _ in 
       expectation.fulfill()
    }
    wait(for: [expec], timeout: 30)
}

请参见Testing Asynchronous Operations with Expectations

注意:

  • 不要像现在那样将单元测试专用代码传递给生产代码。
  • 加载VC不是异步任务。所以不需要期望
  • 您可能不应该直接加载Home类,特别是如果它确实触发了一些异步任务。您应该看看分别测试异步部分并使用Mocks / Stubs

答案 1 :(得分:0)

您需要fulfill期望。像这样:

let expectation = self.expectation(description: "Alert")

DispatchQueue.main.asyncAfter(deadline: .now() + 3.0, execute: {

    expectation.fulfill()
})

waitForExpectations(timeout: 5, handler: nil)

XCTAssert(whatever)