使用XCTest测试Xcode中的计时器

pb3s4cty  于 2023-02-05  发布在  其他
关注(0)|答案(4)|浏览(167)

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

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()让我感觉测试并没有真正告诉我足够的功能。我错过了什么吗?
XC测试:

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

  // Test that my timer has been reset.
}

谢谢!

ymzxtsji

ymzxtsji1#

如果希望等待计时器触发,仍然需要使用expectations(或Xcode 9新的异步测试API)。
问题是你要测试的究竟是什么,你可能不想只测试计时器触发了,而是想测试计时器的处理程序实际上在做什么(假设你有一个计时器来执行一些有意义的事情,所以这就是我们应该测试的)。
WWDC 2017视频Engineering for Testability提供了一个很好的框架来思考如何为单元测试设计代码,这需要:

  • 控制投入;
  • 产出的可见性;以及
  • 没有隐藏状态。

那么,测试的输入是什么?更重要的是,输出是什么?在单元测试中,您希望测试哪些Assert?
该视频还展示了一些实际示例,说明如何通过明智地使用以下内容重构代码以实现此结构:

  • 协议和参数化;以及
  • 分离逻辑和效果。

如果不知道计时器实际在做什么,很难给出进一步的建议。也许你可以编辑你的问题并澄清一下。

qaxu7uf2

qaxu7uf22#

很高兴你找到了解决方案,但回答了标题中的问题;
要测试计时器是否真正工作(即运行和调用回调),我们可以做如下操作:

import XCTest
@testable import MyApp

class MyClassTest: XCTestCase {
    func testStartTimer_shouldTriggerCallbackOnTime() throws {
        let exp = expectation(description: "Wait for timer to complete")
        
        // Dummy.
        let instance: MyClass! = MyClass()
        instance.delay = 2000; // Mili-sec equal 2 seconds.
        instance.callback = { _ in
            exp.fulfill();
        }

        // Actual test.
        instance.startTimer();
        // With pause till completed (sleeps 5 seconds maximum,
        // else resumes as soon as "exp.fulfill()" is called).
        if XCTWaiter.wait(for: [exp], timeout: 5.0) != .completed {
            XCTFail("Timer didn't finish in time.")
        }
    }
}

当有这样的课程时:

public class MyClass {
    public var delay: Int = 0;
    public var callback: ((timer: Timer) -> Void)?
    
    public func startTimer() {
        let myTimer = Timer(timeInterval: Double(self.delay) / 1000.0, repeats: false) {
            [weak self] timer in
            guard let that = self else {
                return
            }
            that.callback?(timer)
        }
        RunLoop.main.add(myTimer, forMode: .common)
    }
}
dsf9zpds

dsf9zpds3#

首先,我会说我不知道你的对象是如何工作的,当你没有任何名为refreshTimer的成员。

class MyClass {
    private var timer:Timer?
    public var  starting:Int = -1 // to keep track of starting time of execution
    public var  ending:Int   = -1 // to keep track of ending time 

    init() {}

    func invoke() {
       // timer would be executed every 10s 
        timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(performAction), userInfo: nil, repeats: true)
        starting = getSeconds()
        print("time init:: \(starting) second")

    }

    @objc func performAction() {
        print("performing action ... ")
        /*
         say that the starting time was 55s, after 10s, we would get 05 seconds, which is correct. However for testing purpose if we get a number from 1 to 9 we'll add 60s. This analogy works because ending depends on starting time  
        */
        ending = (1...9).contains(getSeconds()) ? getSeconds() + 60 : getSeconds()
        print("time end:: \(ending) seconds")
        resetTimer()
    }

    private func resetTimer() {
        print("timer is been reseted")
        timer?.invalidate()
        invoke()
    }

    private func getSeconds()-> Int {
        let seconds = Calendar.current.component(.second, from: Date())
        return seconds 
    }

    public func fullStop() {
        print("Full Stop here")
        timer?.invalidate()
    }
}

测试(注解中的解释)

let testObj = MyClass()
    // at init both starting && ending should be -1
    XCTAssertEqual(testObj.starting, -1)
    XCTAssertEqual(testObj.ending, -1)

    testObj.invoke()
    // after invoking, the first member to be changed is starting
    let startTime = testObj.starting
    XCTAssertNotEqual(startTime, -1)
    /*
    - at first run, ending is still -1 
    - let's for wait 10 seconds 
    - you should use async  method, XCTWaiter and expectation here 
    - this is just to give you a perspective or way of structuring your solution
   */
    DispatchQueue.main.asyncAfter(deadline: .now() + 10 ) {
        let startTimeCopy = startTime
        let endingTime = testObj.ending
        XCTAssertNotEqual(endingTime, -1)
        // take the difference between start and end
        let diff = endingTime - startTime
        print("diff \(diff)")
        // no matter the time, diff should be 10
        XCTAssertEqual(diff, 10)

        testObj.fullStop()
    }

这不是最好的方法,但是它给了你一个关于你应该如何实现这一目标的观点或流程:)

wixjitnu

wixjitnu4#

我最后存储了原始Timer的fireDate,然后检查了执行操作后新的fireDate是否设置为比原始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)
}

相关问题