【问题标题】:Unit testing swift timer function using nimble使用灵活的单元测试快速计时器功能
【发布时间】:2020-05-14 05:31:54
【问题描述】:

我正在使用 Quick、Nimble 和 RxSwift。

我的目标是编写单元测试来测试一些带有 Timer 的功能,这些功能将在一段时间后重复执行。

我的伪类

final class TestingTimerClass {
    let counter: BehaviorRelay<Int> = BehaviorRelay<Int>(value: 0)
    private var timer: Timer?

    ....

    func startTimer() {

        timer = Timer.scheduledTimer(
            timeInterval: 8,
            target: self as Any,
            selector: #selector(self.executeFunction),
            userInfo: nil,
            repeats: true
        )
    }

    @objc private func executeFunction() {
        let currentValue = counter.value
        counter.accept(currentValue + 1)
    }
}

我的测试课

class TestingTimerClass: QuickSpec {

    override func spec() {
        var testingClass: TestingTimerClass!

        describe("executing") {

            context("startTimer()") {

                beforeEach {
                    testingClass = TestingTimerClass()
                }

                afterEach {
                    testingClass = nil
                }

                it("should update counter value after a period of time") {

                    testingClass.startTimer()
                    expect(testingClass.counter.value).toEventually(equal(1), timeout: TimeInterval(9), pollInterval: TimeInterval(2), description: nil)
                }
            }
        }
    }
}

我希望executeFunction() 将在 8 秒后被调用,但它从未被调用,并且我的测试套件失败了。

知道出了什么问题吗?

【问题讨论】:

  • 你需要像testingClass.counter.toBlocking().first() 这样的东西使用RxBlocking 来同步转换异步事件

标签: ios swift rx-swift quick-nimble


【解决方案1】:

您应该减少 Nimble 轮询间隔,因为您的轮询每 2 秒发生一次,以将您的测试类计数器值与每 2 秒的预期值“1”进行比较。

预计 9 秒(超时),但您的最后一次轮询在 8 秒轮询后结束。

将超时时间延长 10 秒以上或缩短轮询间隔以比较超时前的预期值。

提前

您可以通过注入时间间隔或使用 RxTest 来减少您的总测试时间

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多