在RxSwift中测试BehaviorSubject / Relay

时间:2019-01-04 11:09:33

标签: ios swift rx-swift rxtest

我无法测试BehaviorRelay。以下最小限度的代码将可观察对象绑定到BehaviorRelay,但是在测试时,测试不会结束并被挂起-该可观察对象不断发出事件,因为它以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)
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于可观察对象从未完成。添加scheduler.subscribeAt(100) {} 并将提取器设置为nil即可解决问题。