如何使用 Xcode UI 自动化测试在警报文本字段中输入文本

How do I enter text in an alert textfield using Xcode UI Automation testing

这个问题真的很困扰我。阅读了官方文档、Jonathan Penn 的书以及我能找到的所有在线教程。我构建了一个非常简单的应用程序来了解 UI 测试,但在第一步时遇到了困难。它是一个待办事项列表应用程序。我单击 UIBarButtonItem 按钮,它显示一个对话框,其中包含一个 UITextField 和两个按钮,OK 和 Cancel。这是 IBAction。

@IBAction func showDialog(sender: UIBarButtonItem) {
    println("showDialog")
    var inputTextField: UITextField?
    var alert:UIAlertController
    alert = UIAlertController(title: "New Item", message: "Type item below", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Item name"  // need to choose correct keyboard and capitalise first letter of each word.
        inputTextField = textField
    })
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        if let itemName = inputTextField?.text {
            println(itemName)
            self.items.append(itemName)
            self.tableView.reloadData()
        }
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

我尝试通过记录然后添加警报处理程序来编写 UI 自动化测试,但它不起作用。这是我的测试脚本。

var target = UIATarget.localTarget();

UIALogger.logWarning('script started');

target.frontMostApp().navigationBar().rightButton().tap();

UIATarget.onAlert = function onAlert(alert) {
    var title = alert.name();
    UIALogger.logWarning("Alert with title ’" + title + "’ encountered!");
    target.frontMostApp().keyboard().typeString("Cheese");
    alert.buttons()["OK"].tap();
    return true;
}

我做错了什么?

经过大量搜索,我找到了答案。 onAlert 函数只是 returns true 如果我们想与警报交互, false 如果我们只是想关闭它。

var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow();
window.navigationBar().rightButton().tap();

UIATarget.onAlert = function() {
    return true;
}

app.keyboard().typeString("Cheese");
app.alert().buttons()["OK"].tap();