SwiftUI component UITest シリーズ Image 編
Sponsor Link
対象要素の取得
SwiftUI の Image は、accessibility ID を使って取得できます。
XCUIElementTypeQueryProvider からの取得には、images を使用します。
Image を取得
1 2 3 4 5 6 |
let app = XCUIApplication() app.launch() let toggle = app.images["MyImage"] |
状態のチェック
Image に使用されているイメージ名は、label から取得できます。
操作
Image に対して、.onTap 等を指定することもできます。
ですので、テストとしても、tap() 等の操作も可能です。
テストコード例
以下では、TestImage という accessibility ID を付与した Image に対して、tap した後に、表示に使用しているイメージ名をテストしています。
Image テスト例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // (1) let image = app.images["TestImage"] XCTAssertTrue(image.exists) // (2) image.tap() // (3) XCTAssertEqual(image.label, "SampleImage") |
コード解説
- Image を取得
- Image を tap
- Image に設定されているイメージ名をテスト
アプリと、テストコード例
画面に、Image が表示され、その Image をタップすると Image が切り替わるアプリと、そのアプリ用のテストコードです。
Image アプリ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// // ContentView.swift // // Created by : Tomoaki Yagishita on 2020/10/31 // © 2020 SmallDeskSoftware // import SwiftUI struct ContentView: View { @State private var imageName: String = "SampleImage" var body: some View { Image(imageName) .resizable() .scaledToFit() .accessibility(identifier: "TestImage") .padding() .onTapGesture { imageName = "CatImage" } } } |
Image アプリ テストコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
func testImage() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() let image = app.images["TestImage"] XCTAssertTrue(image.exists) XCTAssertEqual(image.label, "SampleImage") image.tap() XCTAssertEqual(image.label, "CatImage") } |
まとめ:SwiftUI の Image をテストする
SwiftUI の Image をテストする
- XCUIApplication から、accessibility ID 指定で Image を取得する
- tap() 等の動作は、他の要素と同様
- 表示している Image は、label から名称を取得できる
説明は以上です。
不明な点やおかしな点ありましたら、ご連絡いただけるとありがたいです。
Sponsor Link