GOAL: I'm currently unit testing the behavior of my UISwitch when it is pressed.
ISSUE: My issue I that the sendActions(for: .valueChanged)
that I use to programmatically change the UISwitch's state is not working as I imagined. It doesn't make it change from false
to true
(in my example).
WHAT DID I DO ?: I'm using the following path:
true
sendActions(for: .valueChanged)
for changing it to false
XCTAssertEqual()
to check if it correctly equal to false
as expected. (I also could have used XCTAssertFalse()
to check directly if it was false
.Ps: I correctly passed loadViewIfNeeded()
in my setUPWithError()
QUESTION: How can I test my UISwitch ??
CODE: Here is my code:
var sut: ViewController!
override func setUpWithError() throws {
super.setUp()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
sut = storyboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController
sut.loadViewIfNeeded()
}
func testGenderButton_ShouldUpdateValueWhenPressed() {
sut.genderSwitch.isOn = true
sut.genderSwitch.sendActions(for: .valueChanged)
XCTAssertEqual(sut.genderSwitch.isOn, false, "\(sut.genderSwitch.isOn) should be equal to false")
}
Don't test it. A UISwitch cannot be a subject-under-test! Unit tests are for logic, not interface, and besides, UISwitch isn't your code — it's Apple's class and you already know how it behaves.