我正在使用Quick、Nimble和RxSwift。
我的目标是编写单元测试,测试一些带有计时器的函数,这些函数将在一段时间间隔后重复执行。
我的伪类
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秒后被调用,但是它从未被调用过,并且我的测试套件失败了。
知道哪里出问题了吗?
发布于 2020-06-06 20:25:05
您应该减少灵活的轮询间隔,因为轮询每隔2秒进行一次,以便将测试类计数器值与预期值“1”每隔2秒比较一次。
预计为9秒(超时),但您的最后一次轮询恰好在8秒轮询后结束。
将超时时间增加到10秒以上或减少轮询间隔以比较超时前的期望值。
高级中的
您可以通过注入时间间隔或使用RxTest来减少您的全部测试时间
https://stackoverflow.com/questions/61789977
复制相似问题