I have a library implementing a custom UIControl
with a method which would fire a .valueChanged
event when called. I would like to test the method for that behavior.
My custom control:
class MyControl: UIControl {
func fire() {
sendActions(for: .valueChanged)
}
}
And the test:
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)
}
}
}
The problem is the observe
method never gets called so the expectation
is not fulfilled.
The question is: how can we test for UIControlEvents
like in this case? Perhaps we need to force the runloop somehow?
EDIT 1:
Please note that since I am testing a library, my test target does not have any Host Application. The test above passes when the test target has a host application.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…