Xcode UI 测试无法编辑多个 UITextFields

Xcode UI test fails to edit multiple UITextFields

我有一个包含多个 UITextField 的 UI,我想通过清除它们的内容并输入新值来测试它们。但是,在 UI 测试中只能更改 first 字段;后续字段可以清除(如果启用了清除按钮),但不能输入(使用XCUIElement.typeText()),因为测试Failed to synthesize event: Neither element nor any descendant has keyboard focus.如何我可以在给定的 UI 测试函数中编辑多个文本字段吗?

我在几个不同的 UI 测试问题中遵循了建议:

UI:

ViewController:

class ViewController: UIViewController {

    @IBOutlet weak var field1: UITextField!
    @IBOutlet weak var field2: UITextField!

    @IBAction func submit(_ sender: Any) {
        let actionVC = UIAlertController(title: "You did it!",
                                         message: "\(field1.text ?? ""), \(field2.text ?? "")",
                                         preferredStyle: .alert)
        actionVC.addAction(UIAlertAction(title: "Awesome!", style: .default, handler: nil))
        present(actionVC, animated: true, completion: nil)
    }

}

测试:

class TextFieldTesterUITests: XCTestCase {

    func testReplaceTextInMultipleTextFields() throws {
        let app = XCUIApplication()
        app.launch()

        let field1TextField = app.textFields["Field 1"]
        field1TextField.tap()
        app.buttons["Clear text"].tap()
        field1TextField.typeText("Oh")

        let field2TextField = app.textFields["Field 2"]
        field2TextField.tap()
        app.buttons["Clear text"].tap() // <-- 
        field2TextField.typeText("Susanna")

        app.staticTexts["Button"].tap()

        app.alerts["You did it!"].scrollViews.otherElements.buttons["Awesome!"].tap()
    }

}

错误:

I've posted this demonstration on GitHub.

正如@Thisura Dodangoda 指出的那样,这段代码在 iOS 14.0.1 和 14.3 上运行正常,我确认它在 15.0 beta 模拟器上运行正常。它似乎只在 iOS 14.5 上出现问题,并且可能在 14.3 和 15.0 之间的其他版本上出现问题。