快速测试包含计时器的方法

问题描述 投票:0回答:2

我是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)


}
ios swift nstimer swift5
2个回答
0
投票
例如:

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增加一以上,则此测试失败...


0
投票
您可以出于测试目的假定Timer有效。

所以...

[测试timer.timeInterval正确,测试timer.target正确,测试timer.selector正确以及测试需要确保正确设置的任何其他属性。

您无需实际运行计时器并等待一秒钟,然后检查是否运行了正确的功能。那将测试Timer的内部工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.