我在ZStack:中有一个带有前景图像的按钮
Button(action: {
self.highlighted = !self.highlighted
}) {
ZStack {
Text("Text")
if self.highlighted {
Image("highlighted").resizable()
}
}
}
只有当变量为true时,前景图像("高亮显示")才可见。单击按钮可翻转高亮显示的变量。因此,如果单击该按钮,它将高亮显示,如果再次单击,它将不再高亮显示。我现在想要一个UiTest,其中点击按钮;突出显示";存在。这就是我所拥有的UiTest,但它在最后一个断言时失败了:
func test_highlight() {
let app = XCUIApplication()
let button = app.buttons["my_button"]
XCTAssertTrue(button.exists)
button.tap()
XCTAssertTrue(button.images["highlighted"].exists) // <-- Fails here
}
这在UiTests中可能吗。如果是,如何?如果没有,还有什么选择?
好的,行了。但老实说,我真的不喜欢在项目文件中写代码只是为了让测试工作。这是一个遗憾,如果这是测试它的唯一方法
我同意,不会使用标识符。然而,公平地说,你所要求的不是我认为你通常在UI测试级别测试的东西吗?
也许通过单元和UI测试资源和业务逻辑(即你的bool)通过快照测试看起来不错?
就我个人而言,我会在这里通过用户集成流程中元素的可访问性/值/标签等来验证UI。
示例
如果将按钮配置为可正确访问,则可以验证按钮的"选定"状态。
let localisedstring = “localised-text”
Button(action: {
self.highlighted = !self.highlighted
}) {
ZStack {
Text(localisedstring)
if self.highlighted {
Image("highlighted").resizable()
}
}
}
.accessibilityTraits(isHighlighted ? [.button, .selected] : [.button])
.accessibilityLabel(localisedString)
然后在测试中你可以做:
// Given base button
let button = app.buttons[“button-id”]
XCTAssertFalse(button.isSelected)
// When user taps
button.tap()
// Then button should be selected
XCTAssertTrue(button.isSelected)
// And whatever-else that button should do
以类似于使用标识符的方式,您使其可测试,并更好地支持画外音等无障碍用户!
编辑:写在我的iPad上,所以请视为伪♂️
辅助功能引擎看不到按钮的内部,但如果您像一样更改
Button(action: {
self.highlighted = !self.highlighted
}) {
if self.highlighted {
Image("highlighted").resizable()
} else {
Text("Text")
}
}
然后你可以通过UT验证切换(使用Xcode 12.1/iOS 14.1测试)
func test_highlight() {
let app = XCUIApplication()
app.launch()
let button = app.buttons["Text"] // << fits button label
XCTAssertTrue(button.exists)
button.tap()
let highlighted_button = app.buttons["highlighted"] // fits button image name
XCTAssertTrue(highlighted_button.exists)
}
更新:透明图像的可能变体
struct DemoView: View {
@State private var highlighted = false
var body: some View {
Button(action: {
self.highlighted = !self.highlighted
}) {
ZStack {
Text("Text")
if self.highlighted {
Image("flag-1").resizable()
}
}
}
.accessibility(identifier: highlighted ? "highlighted" : "button" )
}
}
func test_highlight() {
let app = XCUIApplication()
app.launch()
let button = app.buttons["button"]
XCTAssertTrue(button.exists)
button.tap()
let highlighted = app.buttons["highlighted"]
XCTAssertTrue(highlighted.exists)
}