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

问题描述 投票:0回答:6

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

在调试器中,我可以运行这样的代码来打印出 staticTexts 的所有内容:

po app.staticTexts
。但是如何测试所有内容中的任何位置是否存在字符串?

我可以检查每个静态文本是否存在,执行类似

app.staticTexts["the content of the staticText"].exists
的操作?但我必须使用该静态文本的确切内容。如何仅使用可能只是该内容的一部分的字符串?

swift xctest
6个回答
41
投票

您可以使用

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 谓词编程指南


17
投票

首先,您需要为要访问的静态文本对象设置可访问性标识符。这将允许您找到它,而无需搜索它显示的字符串。

// 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"))

8
投票

我在构建 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)
}

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


4
投票

您可以创建一个扩展来简单地使用它

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")


0
投票
    // Encapsulate your code
    func yourElement() -> XCUIElement {
        let string = "The European languages are members of the same family."
        let predicate = NSPredicate(format: "label CONTAINS[c] '\(string)'")
        return app.staticTexts.matching(predicate).firstMatch
    }

    // To use it
    XCTAssert(yourPage.yourElement().waitForExistence(timeout: 20))

0
投票

这个适用于 SwiftUI

func ensureExists(text: String, inApp: XCUIApplication) {
    let predicate = NSPredicate(format: "value CONTAINS '\(text)'")
    let elementQuery = inApp.staticTexts.containing(predicate)
    XCTAssertTrue (elementQuery.count > 0, "couldn't find \(text)")
}
© www.soinside.com 2019 - 2024. All rights reserved.