简体   繁体   English

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

[英]Unit test Asynchronous wait failed: Exceeded timeout Swift

I am trying to paerform a unit test on my application and majority of the test failed and the reason it says is Asynchronous wait failed: Exceeded timeout of 30 seconds, with unfulfilled expectations: "Home Code". 我试图在我的应用程序上进行单元测试,并且大多数测试失败,并且它说异步等待失败的原因:超过30秒的超时,并且没有实现:“ Home Code”。

I do not know why it fails like this but this is my code below 我不知道为什么它会失败,但这是下面的代码

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
    }
} 

It pops up the simulator but stays on just the first screen. 它会弹出模拟器,但仅停留在第一个屏幕上。 I do not know why. 我不知道为什么。 Any help would be appreciated 任何帮助,将不胜感激

You are not fulfilling your expectations 您没有实现您的期望

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

See Testing Asynchronous Operations with Expectations 请参阅根据预期测试异步操作

Notes: 笔记:

  • Don't pass unit test specific code to production code like you are currently. 不要像现在那样将单元测试特定的代码传递给生产代码。
  • Loading a VC is not an async task. 加载VC不是异步任务。 so shouldn't need an expectation 所以不需要期望
  • You probably shouldn't be loading the Home class directly, especially if it does trigger some async task. 您可能不应该直接加载Home类,尤其是当它确实触发了一些异步任务时。 You should look at testing the async parts seperately and using Mocks/Stubs 您应该看看分别测试异步部分并使用Mocks / Stubs

You need to fulfill the expectation. 您需要fulfill期望。 Like this: 像这样:

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

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

    expectation.fulfill()
})

waitForExpectations(timeout: 5, handler: nil)

XCTAssert(whatever)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM