![](/img/trans.png)
[英]How to pass a value from an EnvironmentObject to a class instance in SwiftUI?
[英]Accessing class instance in XCTest using SwiftUI and @EnvironmentObject
我有一個 SwiftUI 視圖層次結構,其中有一個自定義 class 實例注入 using.environment() 類似於以下內容:
struct ContentView: View {
// Pointer to the AppStateController passed in .environment()
@EnvironmentObject var appStateController: AppStateController
var body: some View {
VStack(spacing: 0) {
TitleView()
.modifier(TitleStyle())
.environmentObject(appStateController)
Spacer()
}
}
}
struct TitleView: View {
@EnvironmentObject var appStateController: AppStateController
var body: some View {
Button(action: {
self.appStateController.isPlaying.toggle()
}, label: {
if self.appStateController.isPlaying {
Image(systemName: "stop.circle")
.opacity(self.appStateController.isPlayable ? 1.0 : 0.5)
.accessibility(label: Text("stop"))
}
else {
Image(systemName: "play.circle")
.opacity(self.appStateController.isPlayable ? 1.0 : 0.5)
.accessibility(label: Text("play"))
}
})
}
}
在 TitleView 上有一堆按鈕,它們的操作會更改 appStateController 中的 @Published 值。 輕按時,這些按鈕還會更改其 label(圖標)。
我剛剛開始進行 UI 單元測試,我已經測試了一個按鈕點擊更改圖標(通過搜索按鈕並檢查它的可訪問性標簽)並且工作正常,但我也想斷言該操作實際上通過檢查 appStateController.isPlaying boolean 來執行某些操作 - 有效地測試我的操作:{} 閉包可以滿足我的需要。
我似乎找不到任何文檔來告訴我,給定一個正在運行的應用程序,我如何通過視圖層次結構找到注入的 appStateController 的引用並檢查其中的屬性。 這可能嗎?如果可以,有誰知道我在哪里可以找到一些關於這樣做的文檔/博客文章?
在 UI 測試中,您測試的是 UI 流程,而不是內部引擎狀態,因此您可以驗證 UI 是否代表正確的 state(即引擎正確完成並且 UI 相應更新)。 為此,它需要識別所需的 UI 元素,然后檢查運行時是否存在所需的元素。
這是可能的方法。 使用 Xcode 11.4 進行測試。
1)在代碼中添加可訪問性標識符
if self.appStateController.isPlaying {
Image(systemName: "stop.circle")
.opacity(self.appStateController.isPlayable ? 1.0 : 0.5)
.accessibility(identifier: "playing") // identify state !!
.accessibility(label: Text("stop"))
}
else {
Image(systemName: "play.circle")
.opacity(self.appStateController.isPlayable ? 1.0 : 0.5)
.accessibility(identifier: "idle")
.accessibility(label: Text("play")) // identify state !!
}
2)在XC測試中
func testPlaying() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// UI manipulations to activate playback
XCTAssertTrue(app.images["playing"].exists)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.