我们有三个状态。我们如何测试(使用单元测试)我们的类,它每 5 秒生成一次随机状态,并且不能连续两次生成相同的状态?我们的随机生成器类的代码如下 ` final class StateRandomGenerator: RandomGeneratorProtocol { private var sourceObservable: Disposable? private(set) var previousValue: Int? var generatedValue: PublishSubject = PublishSubject()
init(_ interval: RxTimeInterval,_ scheduler: SchedulerType = MainScheduler.instance) {
sourceObservable = Observable<Int>
.interval(interval, scheduler: scheduler)
.flatMap { [unowned self] _ in self.generateRandom()}
.compactMap { state in
return state?.description
}
.subscribe(onNext: { [weak self] description in
self?.generatedValue.onNext(description)
})
}
func generateRandom() -> Observable<ConnectionState?> {
return Observable.create { [weak self] observer in
var randomNumber = Int.random(in: 0..<ConnectionState.count)
guard let previousValue = self?.previousValue else {
let value = ConnectionState(rawValue: randomNumber)
self?.previousValue = randomNumber
observer.onNext(value)
return Disposables.create()
}
while randomNumber == previousValue {
randomNumber = Int.random(in: 0..<ConnectionState.count)
}
self?.previousValue = randomNumber
let value = ConnectionState(rawValue: randomNumber)
observer.onNext(value)
return Disposables.create()
}
}
enum ConnectionState: Int {
case error
case connecting
case established
var description: String {
switch self {
case .connecting:
return "It is connecting"
case .error:
return "There is an error"
case .established:
return "Thе connection is established"
}
}
} `