我在测试 BehaviorRelay 时遇到问题。以下最小代码将 observable 绑定到 BehaviorRelay,但在测试时,测试不会结束并挂起 - observable 不断发出事件,因为它以Observable.timer
. 当摆脱该bindRx
方法并仅测试可观察对象时,它可以正常工作。但我想正确地测试课程——这有意义吗?
我该如何做这项工作?
import XCTest
import RxSwift
import RxCocoa
struct TestObject: Codable {
var a: Int?
var b: Int?
private enum CodingKeys: String, CodingKey {
case a = "test"
case b
}
}
extension TestObject: Equatable {
static func == (lhs: TestObject, rhs: TestObject) -> Bool {
return lhs.a == rhs.a && lhs.b == rhs.b
}
}
class TestObjectFetcher {
private let scheduler: SchedulerType
private let disposeBag = DisposeBag()
let testObject = BehaviorRelay<TestObject?>(value: nil)
var syncInterval = 30.0
init(scheduler: SchedulerType) {
self.scheduler = scheduler
self.bindRx()
}
var fetchTestObjectObservable: Observable<TestObject?> {
return Observable<Int>.timer(0, period: self.syncInterval, scheduler: self.scheduler)
.map { _ -> TestObject? in
TestObject(a: 1, b: 2)
}
}
private func bindRx() {
self.fetchTestObjectObservable
.bind(to: self.testObject)
.disposed(by: self.disposeBag)
}
}
class TestObjectFetcherTests: XCTestCase {
let testScheduler = TestScheduler(initialClock: 0)
func testTestObjectFetcher() {
let testObjectFetcher = TestObjectFetcher(scheduler: testScheduler)
let events: [Recorded<Event<TestObject?>>] = [
Recorded.next(1, TestObject(a: 1, b: 2)),
Recorded.next(31, TestObject(a: 1, b: 2)),
Recorded.next(61, TestObject(a: 1, b: 2))
]
let res = testScheduler.start(created: 0, subscribed: 0, disposed: 90) { () -> Observable<TestObject?> in
return testObjectFetcher.testObject.asObservable()
}
XCTAssertEqual(res.events, events)
}
}