gpt4 book ai didi

swift - 单元测试定时器?

转载 作者:行者123 更新时间:2023-11-28 11:34:38 24 4
gpt4 key购买 nike

我想测试每 6 秒触发一次信号。我的代码如下所示:

class DataStore {

var clinics: Int { return clinicsSignal.lastDataFired ?? 0 }
let clinicsSignal = Signal<Int>(retainLastData: true)
var timer: Timer?

init() {
}

func load() {

self.clinicsSignal.fire(0)

DispatchQueue.main.async { [weak self] in
self!.timer?.invalidate()
self!.timer = Timer.scheduledTimer(withTimeInterval: 6.0, repeats: true) { [weak self] _ in
self?.clinicsSignal.fire(9)
}
}
}
}

我的测试代码是这样的:

func testRefresh() {

var dataStore: DataStore = DataStore()

dataStore.clinicsSignal.subscribeOnce(with: self) {
print("clinics signal = \($0)")
dataStore.clinicsSignal.fire(0)
}

dataStore.load()

sleep(30)

print("clinics3 = \(dataStore.clinics)")

}

当我 sleep 30 秒时,计时器代码直到 30 秒后才会再次运行,因此它不会像预期的那样每 6 秒运行一次。关于如何在计时器中测试该代码的任何想法都会在特定时间被击中?谢谢。

最佳答案

sleep 函数会阻塞您的线程,并且计时器与线程相关联。您应该使用 expectation

func testRefresh() {

var dataStore: DataStore = DataStore()
let expec = expectation(description: "Timer expectation") // create an expectation
dataStore.clinicsSignal.subscribeOnce(with: self) {
print("clinics signal = \($0)")
dataStore.clinicsSignal.fire(0)
expec.fulfill() // tell the expectation that everything's done
}

dataStore.load()
wait(for: [expec], timeout: 7.0) // wait for fulfilling every expectation (in this case only one), timeout must be greater than the timer interval
}

关于swift - 单元测试定时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870601/

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