UITesting, XCTest current ViewController Class

后端 未结 2 1092
半阙折子戏
半阙折子戏 2021-02-07 00:34

Simple problem. I got button which perform segue to next view controller. I want to write UI XCTest to tell me did it open view controller i wanted.

2条回答
  •  死守一世寂寞
    2021-02-07 01:33

    Comment of Matt Green gave me a good idea. We can define an unused label/button, ideally inside a base view controller and assign it an accessibility label to perform a query to find out which view controller is presented.

    public class BaseViewController: UIViewController {
    
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
    
        public override func viewDidLoad() {
            super.viewDidLoad()
            if let identifier = self.theClassName.split(separator: ".").last {
                button.accessibilityIdentifier = String(identifier)
                view.addSubview(button)
            }
        }
    }
    
    public class DatePickerViewController: BaseViewController {
       ...
    }
    
    func testExample() {
        let app = XCUIApplication()
        app.launch()
        app.navigationBars.buttons["DateSelector"].tap()
        XCTAssertTrue(app.buttons["DatePickerViewController"].exists)
    }
    

    Note that inorder to make this approach work you have to add the view you use to identify view controller, in this case a button, should be added as a sub view and has to have a non zero frame.

提交回复
热议问题