如何使用 XCTest 测试 staticTexts 是否包含字符串 [英] How to test that staticTexts contains a string using XCTest

查看:15
本文介绍了如何使用 XCTest 测试 staticTexts 是否包含字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Xcode UI testing, how do I test that staticTexts contains a string?

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

In the debugger, I can run something like this to print out all the content of staticTexts: po app.staticTexts . But how do I test if a string exists anywhere within all of that content?

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

I can check for the existence of each staticText doing something like app.staticTexts["the content of the staticText"].exists? but I have to use the exact content of that staticText. How can I use only a string which may be only a part of that content?

推荐答案

首先,您需要为要访问的静态文本对象设置一个可访问性标识符.这将允许您在不搜索它显示的字符串的情况下找到它.

First, you need to set an accessibility identifier for the static text object you want to access. This will allow you to find it without searching for the string it is displaying.

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

然后你可以通过在XCUIElement上调用.label来编写测试来断言显示的字符串是否是你想要的字符串:

Then you can assert whether the string displayed is the string you want by writing a test by calling .label on the XCUIElement to get the contents of the displayed string:

// 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.

To check it contains a certain string, use range(of:), which will return nil if the string you give is not found.

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

这篇关于如何使用 XCTest 测试 staticTexts 是否包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆