【问题标题】:How to access a SwiftUI view's property from a UI Test case class?如何从 UI 测试用例类访问 SwiftUI 视图的属性?
【发布时间】:2025-12-19 17:10:07
【问题描述】:

我正在编写 UI 测试,我需要访问视图的 @State 属性,只要该视图内的按钮即可。

struct CircleImage: View {

    @State var imageName: String = ""

    var body: some View {
        // ...
        Button(action: {}) {}
        .accessibility(identifier: "myButton")
    }
}

我很容易通过let myButton = app.buttons["myButton"] 获得按钮。但出于测试目的,我还需要访问 imageName 属性。我尝试在 ContentView 中添加 CircleImage().accessibility(identifier: "circleImageView"),但它会覆盖 CircleImage 视图(包括按钮)内的所有可访问性(标识符:)。

【问题讨论】:

标签: swift swiftui xcode-ui-testing


【解决方案1】:

UI 测试不测试内部状态。他们只测试 UI 可见的行为。要针对这种类型编写 UI 测试,imageName 应该会产生一些行为,然后您测试该行为是否可见。在这种情况下,您可以将 imageName 转换为可访问性标签,这将允许 VoiceOver 读取它(顺便还允许 UI 测试访问它)。

The best way to make an app UI-testable is to first make it accessible. 使用 VoiceOver 试用您的应用。如果它在那里运行良好,那么它很可能也适用于 UI 测试。

【讨论】: