如何从 UI 测试用例 class 访问 SwiftUI 视图的 属性?

How to access a SwiftUI view's property from a UI Test case class?

我正在编写 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 视图(包括按钮)内的所有可访问性(标识符:)。

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

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