使用敏捷的单元测试快速计时器功能

问题描述 投票:1回答:1

我正在使用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秒后被调用,但是从不调用它,并且我的测试套件失败了。

任何想法出了什么问题?

ios swift rx-swift quick-nimble
1个回答
0
投票

您应缩短Nimble轮询间隔,因为您的轮询每2秒进行一次,以将您的测试类计数器值与每2秒的期望值'1'进行比较。

预计等待9秒(超时),但您的上一次轮询恰好在8秒钟的轮询后结束。

将超时增加10秒钟以上,或减少轮询间隔以比较超时之前的期望值。

提前

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

© www.soinside.com 2019 - 2024. All rights reserved.