使用 XCTest 在 Xcode 中测试计时器 [英] Testing a Timer in Xcode with XCTest

查看:30
本文介绍了使用 XCTest 在 Xcode 中测试计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不需要每 10 秒调用一次的函数.每次调用该函数时,我都会将计时器重置为 10 秒.

I have a function that does not need to be called any more than every 10 secs. Every time I invoke the function, I reset the timer to 10 secs.

class MyClass {
  var timer:Timer?

  func resetTimer() {
    self.timer?.invalidate()
    self.timer = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: false) {
      (timer) -> Void in
      self.performAction()        
    }
  }

  func performAction() {
    // perform action, then
    self.resetTimer()
  }
}

我想测试调用 performAction() 手动将计时器重置为 10 秒,但我似乎找不到任何好的方法来做到这一点.存根 resetTimer() 感觉测试并不能真正告诉我足够的功能.我错过了什么吗?

I would like to test that calling performAction() manually resets the timer to 10 secs, but I can't seem to find any good way to do it. Stubbing resetTimer() feels like the test wouldn't really be telling me enough about the functionality. Am I missing something?

XCTest:

func testTimerResets() {
  let myObject = MyClass()
  myObject.resetTimer()
  myObject.performAction()

  // Test that my timer has been reset.
}

谢谢!

推荐答案

我最终存储了原始 Timer 的 fireDate,然后检查以查看在执行操作后新的 fireDate 设置为比原始 fireDate 晚的某个时间.

I ended up storing the original Timer's fireDate, then checking to see that after the action was performed the new fireDate was set to something later than the original fireDate.

func testTimerResets() {
  let myObject = MyClass()
  myObject.resetTimer()
  let oldFireDate = myObject.timer!.fireDate
  myObject.performAction()

  // If timer did not reset, these will be equal
  XCTAssertGreaterThan(myObject.timer!.fireDate, oldFireDate)
}

这篇关于使用 XCTest 在 Xcode 中测试计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆