Search code examples
swiftxcodetimerxctest

Testing a Timer in Xcode with XCTest


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()
  }
}

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.
}

Thanks!


Solution

  • 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)
    }