How to test if a UIControlEvents has been fired

后端 未结 2 678
太阳男子
太阳男子 2020-12-18 12:05

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

2条回答
  •  佛祖请我去吃肉
    2020-12-18 12:28

    You are declaring the observer object inside the test method. This means that as soon as the method completes it will be released from memory and hence is not called. Create a reference to the observer at class level in the Tests class as follows and it will work.

    class Tests: XCTestCase {
    
        var observer: ControlEventObserver!
        func test() {
            let myExpectation = expectation(description: "event fired")
            self.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)
            }
        }
    }
    

    You will also need the myExpectation & control to be declared in the same way else that won't be called either.

提交回复
热议问题