我是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增加一以上,则此测试失败...
Timer
有效。所以...
[测试timer.timeInterval
正确,测试timer.target
正确,测试timer.selector
正确以及测试需要确保正确设置的任何其他属性。
您无需实际运行计时器并等待一秒钟,然后检查是否运行了正确的功能。那将测试Timer
的内部工作原理。