当文本字段为空时,如何在 Xcode UI 测试中测试 UITextField?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34658482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:23:39  来源:igfitidea点击:

How to test UITextField in Xcode UI Testing when the text field is empty?

iosobjective-cxcodeuitextfieldxcode-ui-testing

提问by Anuj Kalra

I am making a UITestin Xcode. When I record my test it works fine but when I run the test, it gives an error.

我正在UITestXcode 中制作一个。当我记录我的测试时它工作正常,但是当我运行测试时,它给出了一个错误。

These are the lines of code where the error occurs:

这些是发生错误的代码行:

XCUIElement *clearTextTextField = [app.textFields containingType:XCUIElementTypeButton 
                                                      identifier:@"Clear text"].element;
[clearTextTextField typeText:@"sheffield"];

The error says

错误说

UI Testing Failure - No matches found for textfield

UI 测试失败 - 找不到文本字段的匹配项

I imagine this is because my Text Field does not have any initial string and the tester cannot find a text box with initial string "Clear Text".

我想这是因为我的 Text Field 没有任何初始 string 并且测试人员找不到带有 initial string 的文本框"Clear Text"

I watched the following tutorial on youtube.

在youtube上观看了以下教程。

The demonstrators code turns out fine because his textfield has an initial string. (At least that is what I think the problem is)

演示者代码结果很好,因为他的文本字段有一个初始字符串。(至少这是我认为的问题所在)

Is there a way to make the test work for empty text fields?

有没有办法让测试适用于空文本字段?

采纳答案by Alex

There are a few ways to do this.

有几种方法可以做到这一点。

  1. If the textField has placeholder text you can use the placeholder text to find the textField.

  2. You can use the elementBoundByIndexmethod to get a textField at an index. i.e. If that is the only textField in the app at the time you can use

    XCUIApplication().textFields.elementBoundByIndex(0) 
    
  1. 如果 textField 有占位符文本,您可以使用占位符文本来查找 textField。

  2. 您可以使用该elementBoundByIndex方法在索引处获取 textField。即如果这是当时应用程序中唯一的 textField,您可以使用

    XCUIApplication().textFields.elementBoundByIndex(0) 
    

to get the textField. (or whatever query you need to get that particular textField at that time)

获取文本字段。(或当时需要获取该特定 textField 的任何查询)

  1. You can set an accessibility identifier in code or in the storyboard to find the textField.
  1. 您可以在代码或故事板中设置可访问性标识符以查找 textField。

It is nice to use option 2 before setting up accessibility identifiers, so long as your textField is always going to be findable with the same query. Also, option 1 will fail if multiple textFields have the same placeholder text at the same time, so option 2 is even more appealing.

在设置可访问性标识符之前使用选项 2 很好,只要您的 textField 始终可以使用相同的查询找到。此外,如果多个 textField 同时具有相同的占位符文本,则选项 1 将失败,因此选项 2 更具吸引力。