SwiftUI component UITest シリーズ Text 編

Sponsor Link
対象要素の取得
SwiftUI の Image は、accessibility ID を使って取得できます。
XCUIElementTypeQueryProvider からの取得には、staticTexts を使用します。
Text を取得
1 2 3 4 5 6 |
let app = XCUIApplication() app.launch() let text = app.staticTexts["MyText"] |
状態のチェック
Text に設定されているテキストは、label から取得できます。
操作
Text に対して、.onTap 等を指定することもできます。
ですので、テストとしても、tap() 等の操作も可能です。
テストコード
以下では、MyTest という accessibility ID を付与した Text に対して、設定されているテキストをテストしています。
Text テスト例
1 2 3 4 5 6 7 8 9 |
// UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // (1) let text = app.staticTexts["MyText"] // (2) XCTAssertEqual(text.label, "ExpectedString") |
コード解説
- Text を取得
- Text に設定されているテキストをテスト
アプリとテストコード例
画面に、”Hello, world!” と表示されるアプリと、そのアプリ用のテストコードです。
HelloWorld アプリ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// // ContentView.swift // // Created by : Tomoaki Yagishita on 2020/11/11 // © 2020 SmallDeskSoftware // import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .accessibility(identifier: "MyText") .font(.largeTitle) .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } |
Image アプリ テストコード
1 2 3 4 5 6 7 8 9 10 11 |
func testText() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() let text = app.staticTexts["MyText"] XCTAssertEqual(text.label, "Hello, world!") } |
まとめ:SwiftUI の Text をテストする
SwiftUI の Text をテストする
- XCUIApplication から、accessibility ID 指定で、staticTexts から Text を取得する
- tap() 等の動作は、他の要素と同様
- 表示している 文字列 は、label から取得できる
説明は以上です。Happy Coding !
Sponsor Link