首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用nimble对快速计时器功能进行单元测试

使用nimble对快速计时器功能进行单元测试
EN

Stack Overflow用户
提问于 2020-05-14 13:31:54
回答 1查看 398关注 0票数 2

我正在使用Quick、Nimble和RxSwift。

我的目标是编写单元测试,测试一些带有计时器的函数,这些函数将在一段时间间隔后重复执行。

我的伪类

代码语言:javascript
复制
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)
    }
}

我的测试类

代码语言:javascript
复制
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秒后被调用,但是它从未被调用过,并且我的测试套件失败了。

知道哪里出问题了吗?

EN

回答 1

Stack Overflow用户

发布于 2020-06-06 20:25:05

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

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

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

高级中的

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61789977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档