2016-01-06 45 views
2

我在項目中使用ModelView-ViewModel我目前的工作和使用RxSwiftRxBlocking & RxTests測試視圖模型。目前我正在嘗試測試ViewModel,但有許多麻煩讓我想起這件事。與RxSwift

所以可以說我有我的ExampleViewControllerExampleViewModel。我的ExampleViewModel期待一個Observable流是兩個流從UITextField的組合(combineLatest),一個是如果文本框或者是聚焦而另一個是文本的流;所以像Observable<(Bool, String)>。取決於是否重點和字符串的上下文我的ExampleViewModel將發出一個事件到其內部暴露的屬性,這是ObservableUITextField的backgroundColor狀態; Observable<UIColor>

ExampleViewModel.swift

class ExampleViewModel { 

private let disposeBag = DisposeBag() 

private let _textFieldColor: PublishSubject<UIColor> 
var textFieldColor: Observable<UIColor> { get { return self._textFieldColor.asObservable() } } 

init(textFieldObservable: Observable<(Bool, String)>) { 
    textFieldObservable.subscribeNext { (focus, text) in 
     self.validateTextField(focus, text: text) 
    }.addDisposableTo(self.disposeBag) 
} 

func validateTextField(focus: Bool, text: String) { 
    if !focus && !text.isEmpty { 
     self._textFieldColor.onNext(UIColor.whiteColor()) 
    } else { 
     self._textFieldColor.onNext(UIColor.redColor()) 
    } 
} 
} 

(對不起,我不知道如何將它正確地格式化)

基本上我想通過控制測試ExampleViewModel類和測試,它發出了正確的UIColor重點和文字輸入。

感謝

回答

0

感謝我的同事的建議下,我發現關於構建ExampleViewModel可測試性更好的辦法。通過將驗證方法與ExampleViewModel分開,並使用map運算符設置textFieldColorObservable,其中驗證程序在其中使用,驗證在外部完成並且不使用簡化邏輯測試的Rx

ExampleViewModel

class ExampleViewModel { 

var textFieldColor: Observable<UIColor> 

init(
    textFieldText: Observable<String>, 
    textFieldFocus: Observable<Bool>, 
    validator: TextFieldValidator 
) { 
    self. textFieldColor = Observable.combineLatest(textFieldText, textFieldFocus) { ($0, $1) }. map { validator.validate($1, text: $0) } 
} 
} 



class TextFieldValidator { 

func validate(focus: Bool, text: String) -> UIColor { 
    if !focus && !text.isEmpty { 
     return UIColor.whiteColor() 
    } else { 
     return UIColor.redColor() 
    } 
} 
}