如何测试staticTexts包含使用XCTest的字符串

时间:2016-06-27 00:21:40

标签: swift xctest

在Xcode UI测试中,如何测试staticTexts是否包含字符串?

在调试器中,我可以运行类似这样的东西来打印出staticTexts的所有内容:po app.staticTexts。但是,如何测试字符串是否存在于所有内容中的任何位置?

我可以检查每个staticText是否存在像app.staticTexts["the content of the staticText"].exists这样的东西?但我必须使用该staticText的确切内容。我怎样才能只使用可能只是该内容一部分的字符串?

4 个答案:

答案 0 :(得分:16)

您可以使用NSPredicate过滤元素。

  let searchText = "the content of the staticText"
  let predicate = NSPredicate(format: "label CONTAINS[c] %@", searchText)
  let elementQuery = app.staticTexts.containing(predicate)
  if elementQuery.count > 0 {
    // the element exists
  }

使用CONTAINS[c]指定搜索不区分大小写。

查看Apples Predicate Programming Guide

答案 1 :(得分:5)

我在构建我的XCTest时遇到了这个问题,我在我应该验证的文本块中有一个动态字符串。我已经构建了这两个函数来解决我的问题:

func waitElement(element: Any, timeout: TimeInterval = 100.0) {
    let exists = NSPredicate(format: "exists == 1")

    expectation(for: exists, evaluatedWith: element, handler: nil)
    waitForExpectations(timeout: timeout, handler: nil)
}

func waitMessage(message: String) {
    let predicate = NSPredicate(format: "label CONTAINS[c] %@", message)
    let result = app.staticTexts.containing(predicate)
    let element = XCUIApplication().staticTexts[result.element.label]
    waitElement(element: element)
}

我知道这篇文章很老,但我希望这可以帮助别人。

答案 2 :(得分:4)

首先,您需要为要访问的静态文本对象设置辅助功能标识符。这将允许您在不搜索正在显示的字符串的情况下找到它。

// Your app code
label.accessibilityIdentifier = "myLabel"

然后你可以通过调用XCUIElement上的.label来获取显示字符串的内容,从而断言显示的字符串是否是你想要的字符串:

// Find the label
let myLabel = app.staticTexts["myLabel"]
// Check the string displayed on the label is correct
XCTAssertEqual("Expected string", myLabel.label)

要检查它是否包含某个字符串,请使用range(of:),如果找不到您提供的字符串,则会返回nil

XCTAssertNotNil(myLabel.label.range(of:"expected part"))

答案 3 :(得分:0)

您可以创建扩展程序,以仅在XCUIElement上使用它。

extension XCUIElement {
    
    func assertContains(text: String) {
        let predicate = NSPredicate(format: "label CONTAINS[c] %@", text)
        let elementQuery = staticTexts.containing(predicate)
        XCTAssertTrue(elementQuery.count > 0)
    }
}

用法:

// Find the label
let yourLabel = app.staticTexts["AccessibilityIdentifierOfYourLabel"].firstMatch

// assert that contains value
yourLabel.assertContains(text: "a part of content of the staticText")