![](/img/trans.png)
[英]In XCTest: how to test that a function forced execution onto main thread
[英]How to test a function that gets into the main thread in Swift with RxSwift and XCTest?
我在測試View時遇到了這個問題:
在我的ViewModel中,我調用一個異步操作,當響應到達時,我使用PublishSubject
在View中進行更改。 在我的視圖中,我調用DispatchQueue.main.async
以隱藏或顯示按鈕。
視圖模型
let refreshButtons = PublishSubject<Bool>(true)
refreshButtons.onNext(true)
視圖
model.refreshButtons.asObservable()
.subscribe(onNext: {
[unowned self] success in
self.updateButtons(success)
})
.addDisposableTo(disposable)
private func updateButtons(_ show:Bool) {
DispatchQueue.main.async{
button.isHidden = !show
}
}
現在,我不知道如何對refreshButtons.onNext(true)
將隱藏或顯示我的按鈕進行單元測試。
我能想到的解決方案是:
我該如何解決? 先感謝您。
您可以在單元測試中使用基於謂詞的異步期望,以等待按鈕不再被隱藏。
func testButtonIsHidden() {
// Setup your objects
let view = ...
let viewModel = ...
// Define an NSPredicate to test your expectation
let predicate = NSPredicate(block: { input, _ in
guard let _view = input as? MyView else { return false }
return _view.button.isHidden == true
})
// Create an expectation that will periodically evaluate the predicate
// to decided whether it's fulfilled or not
_ = expectation(for: predicate, evaluatedWith: view, handler: .none)
// Call the method that should generate the behaviour you are expecting.
viewModel.methodThatShouldResultInButtonBeingHidden()
// Wait for the
waitForExpectationsWithTimeout(1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
值得注意的是,您傳遞給NSPredicate
的值應該是一個class
。 那是因為類是通過引用傳遞的,所以謂詞塊中的值將與視圖模型所觸及的值相同。 如果要傳遞通過副本傳遞的struct
或enum
,則謂詞塊將在運行安裝代碼時按原樣接收值的副本,並且它將始終失敗。
相反,如果您更喜歡使用@Randall Wang在其答案中建議的UI測試,則此文章可能對您有用:“ 如何在Xcode 7中測試UI更改 ”。 完全公開,我寫了那個帖子。
首先,您不需要測試私有方法
如果要測試按鈕是否隱藏,請嘗試進行UI測試
這是UI測試的WWDC。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.