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

Kin*_*ing 5 unit-testing swift

我正在尝试对我的应用程序进行单元测试,大部分测试失败,原因是异步等待失败:超过 30 秒超时,未实现预期:“Home Code”。

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

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
    }
} 
Run Code Online (Sandbox Code Playgroud)

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

Scr*_*ble 4

你没有达到你的期望

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

请参阅按预期测试异步操作

笔记:

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