swiftunit-testinguikitxctestuiswitch

UISwitch Unit test with sendActions(for: .valueChanged)


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:

  1. I declared my UISwitch as true
  2. I used sendActions(for: .valueChanged) for changing it to false
  3. I finally used 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")
    }

Solution

  • 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.