含弯引号的可变标签staticText断言失败问题排查
问题:断言带弯引号的动态StaticText失败原因分析
问题背景
需要断言屏幕上生成的staticText是否存在,该staticText的标签规则为:
- 核心内容是用户输入的可变文本
- 应用自动在文本首尾添加弯引号(例如输入
abc时,标签为“abc”)
测试代码
func test() throws { // 模拟输入部分 let searchTerm = "abc" app.typeText(searchTerm) // 固定字符串断言有效,但需基于可变内容断言 XCTAssertTrue(app.staticTexts["“abc”"].exists) // 拼接用于查找staticText的字符串 let staticTextLabel = "”\(searchTerm)”" // 此处断言失败,提示staticText不存在(无弯引号的可变标签断言正常) XCTAssertTrue(app.staticTexts[staticTextLabel].exists) }
调试控制台输出
po app.staticTexts --> StaticText, 0x7ff12af25b50, {...}, label: '“abc”' po staticTextLabel --> "”abc”" po app.staticTexts["“abc”"].exists --> True po app.staticTexts[staticTextLabel].exists --> False
问题
无弯引号的可变staticText断言可正常工作,请问忽略了什么?
问题原因及解决方案
核心原因
你拼接查找字符串时用错了弯引号的方向:
应用生成的标签是**左弯引号(“)**开头、**右弯引号(”)**结尾,但代码中拼接的是"”\(searchTerm)”"——开头误用了右弯引号,导致拼接出的字符串和实际标签完全不匹配,因此断言失败。
修正代码
将拼接字符串的开头改为左弯引号即可:
func test() throws { let searchTerm = "abc" app.typeText(searchTerm) // 修正:开头用左弯引号,结尾用右弯引号 let staticTextLabel = "“\(searchTerm)”" XCTAssertTrue(app.staticTexts[staticTextLabel].exists) }
验证方法(可选)
可以通过打印Unicode编码确认引号差异:
// 打印实际标签引号的Unicode值 print("左弯引号Unicode: \(UnicodeScalar("“")!.value)") // 输出 8220 print("右弯引号Unicode: \(UnicodeScalar("”")!.value)") // 输出 8221 // 打印错误拼接字符串的首尾引号Unicode let wrongLabel = "”abc”" print("错误开头引号Unicode: \(UnicodeScalar(wrongLabel.first!)!.value)") // 输出 8221
可见错误拼接的开头引号Unicode和实际标签的开头引号不一致,这就是查找失败的根本原因。
内容的提问来源于stack exchange,提问作者FY SerranoU
相关产品推荐
相关产品推荐

