UISlider addTarget and sendActions not working in UTs

Viewed 1916

When I run this code in a standard MVC project, all works fine: I can programmatically send actions to my UISlider.

override func viewDidLoad() {
    super.viewDidLoad()        
    slider = UISlider(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
    slider.minimumValue = 1
    slider.maximumValue = 100
    slider.addTarget(self, action: #selector(sliderTouch), for: .touchUpInside)
    slider.sendActions(for: .touchUpInside)
}

func sliderTouch(sender: UISlider) {
    print("value: \(sender.value)")
}

Now for some reason, when I want to simulate Slider behaviors in my UTs, it's not working. here is the code:

func testSlider() {
    let slider = UISlider(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
    slider.minimumValue = 1
    slider.maximumValue = 100
    slider.addTarget(self, action: #selector(sliderTouch), for: .touchUpInside)
    slider.sendActions(for: .touchUpInside)
}

func sliderTouch(sender: UISlider) {
    print("value: \(sender.value)")
}

sliderTouch() is never called in the UT case and from my understanding, sendActions is not asnyc and should directly call the action methods.

So why am I getting this behavior, and how can I solve this?

Edit: I also need it to work for other UIKit controls such as UISwitch, UISegmentedControl, UIDatePicker etc...

2 Answers
Related