gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:14:30 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com