ios - Swift 对包含计时器的方法进行单元测试

标签 ios swift nstimer swift5

我是 swift 和 swift 单元测试的新手。在 MyClass 的代码中,我使用计时器来触发某些方法.. 我需要对具有计时器计数值的方法进行单元测试。 我检查了几个答案。没有任何结果。 我无法做到这一点。谁能帮我解决这个问题。 提前致谢。

 class MyClass(){

func triggerSecondTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(repeatSecondTimer), userInfo: nil, repeats: true)
}

@objc func repeatSecondTimer(){
    timerCount += 1
    if isServiceCallComplete || timerCount == secondInterval {
        timer?.invalidate()
        finishedSecondTimer()
    }
}
}
   func testSecondTimer() {

    splashScreenMock.triggerSecondTimer()
   // I want to check the timer count here..

    XCTAssertEqual(self.splashScreenMock.timerCount, 20)


}

最佳答案

你应该使用期望。

例如:

func testSecondTimer() {
    let myObj = MyClass()
    let expectation = self.expectation(description: #function)
    let expectedTime: Double = 2

    myObj.triggerSecondTimer()
    DispatchQueue.main.asyncAfter(deadline: .now() + expectedTime) {
        expectation.fulfill()
    }

    waitForExpectations(timeout: expectedTime+1)
    XCTAssertEqual(myObj.timerCount, Int(expectedTime))
}

如果在repeatSecondTimer方法中timerCount增加超过1,则此测试失败...

关于ios - Swift 对包含计时器的方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321364/

相关文章:

ios - 如何知道用户是否更改了选项卡?

ios - 从 iTunesConnect 中(永久)删除应用程序后重新使用相同的包 ID

ios - 将 xcode 6 beta 6 升级到 xcode 6 GM 种子后出现 Swift 编译器错误

swift - 特定功能同时在所有 View 上运行。我怎样才能让它一个接一个地运行?

swift - 使用 NSDate 和 NSTimer 进行游戏计时器? swift

iphone - 查找 NSTimer 是否无效

ios - 推送通知以进行即时消息传递

ios - 某些设备上的联系人加载速度太慢

ios - FirebaseHandle 上的编译错误

ios - 离开应用程序并返回 ios 时的计时器