0

我正在尝试为DriverRxCocoa 库编写一个单元测试。这是我的简化实现代码:

struct LoginViewModel {

    var username: Driver<String?>!
    var password: Driver<String?>!
    var loginTaps: Driver<Void>!

    func login() -> Driver<LoginResult> {
        let credentials = Driver.combineLatest(username, password) { ($0, $1) }
        let latestCredentials = loginTaps.withLatestFrom(credentials)

        return latestCredentials.flatMapLatest { (username, password) in
            .just(.success)
        }
    }
}

这是我试图通过的 Quick/Nimble 单元测试:

let disposeBag = DisposeBag()
var capturedLoginResult = LoginResult.failed

loginViewModel.username = Driver.just("some username")
loginViewModel.password = Driver.just("some password")
loginViewModel.loginTaps = Driver.just()

loginViewModel.login().drive(onNext: { loginResult in
    capturedLoginResult = loginResult
}).addDisposableTo(disposeBag)

expect(capturedLoginResult == .success)

上面expectcapturedLoginResult的还是.failed。似乎元素 from在测试return latestCredentials.flatMapLatest { (username, password) in .just(.success) }中没有被接收.drive(onNext: )

如果执行login只是:

func login() -> Driver<LoginResult> {
    return .just(.success)
}

测试通过。

对这里发生的事情有任何想法吗?谢谢!

4

1 回答 1

1

我不知道 Rx 的确切来源在哪里,但我猜你正在使用的操作员正在切换调度程序。因此,使用的订阅drive(onNext:)不会立即触发。

RxSwift 通过RxTest包提供了一个很好的 API 来测试我们的 observables。你可以重写你的测试来利用它。

let scheduler = TestScheduler(initialClock: 0)
let username = scheduler.createHotObservable([next(220, "username"), completed(20)])
let password = scheduler.createHotObservable([next(230, "p4ssw0rd"), completed(20)])
let loginTaps = scheduler.createHotObservable([next(240), completed(20)]) 

let recordObserver = scheduler.start(300) { () -> Observable<LoginResult> in
  let loginViewModel = LoginViewModel()

  loginViewModel.username = username.asDriver(onErrorJustReturn: "")
  loginViewModel.password = username.asDriver(onErrorJustReturn: "")
  loginViewModel.loginTaps = loginTaps.asDriver(onErrorJustReturn: ())

  return loginViewModel.login().asObservable()
}

let expectedEvents: [Recorded<Event<LoginResult>>] = [
  next(240, Login.success)
]

expect(recordObserver.events) == (expectedEvents)
于 2017-03-03T01:41:36.253 回答