我有一個庫實現自定義UIControl
的方法,該方法在調用時會觸發一個.valueChanged
事件。我想測試該行爲的方法。如何測試UIControlEvents是否已被觸發
我的自定義控件:
class MyControl: UIControl {
func fire() {
sendActions(for: .valueChanged)
}
}
而且測試:
import XCTest
class ControlEventObserver: NSObject {
var expectation: XCTestExpectation!
init(expectation anExpectation: XCTestExpectation) {
expectation = anExpectation
}
func observe() {
expectation.fulfill()
}
}
class Tests: XCTestCase {
func test() {
let myExpectation = expectation(description: "event fired")
let observer = ControlEventObserver(expectation: myExpectation)
let control = MyControl()
control.addTarget(observer, action: #selector(ControlEventObserver.observe), for: .valueChanged)
control.fire()
waitForExpectations(timeout: 1) { error in
XCTAssertNil(error)
}
}
}
的問題是observe
方法不會被調用,因此expectation
沒有實現。
問題是:我們如何在這種情況下測試UIControlEvents
?也許我們需要以某種方式強制runloop?
編輯1: 請注意,由於我正在測試庫,我的測試目標沒有任何主機應用程序。當測試目標具有主機應用程序時,上述測試通過。
這很奇怪我已經在我創建的項目中複製並粘貼了您的代碼,並且期望已全滿,測試成功通過。 – Wilson
剛剛意識到這可能是因爲我正在測試一個庫。當我使用主機應用程序創建另一個測試目標時,上面的測試通過。 @WilsonBalderrama –