【问题标题】:Unit Testing a Timer?对计时器进行单元测试?
【发布时间】:2019-04-26 15:20:24
【问题描述】:

我想测试每 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)")

}

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

【问题讨论】:

  • 为什么你的班级是final
  • @RicoCrescenzio 会有什么不同吗?!
  • @RicoCrescenzio 好问题。我只是把它拿出来了。我不知道为什么会这样。

标签: swift asynchronous time timer


【解决方案1】:

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
}

【讨论】:

  • 也许我的代码不能解决你的问题(因为我注意到它有点复杂),但是在处理异步测试时一般的方法是这样
猜你喜欢
  • 2020-11-30
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
相关资源
最近更新 更多