SwiftUI component UITest シリーズ Button 編
Sponsor Link
対象要素の取得
SwiftUI の Button は、accessibility ID を使って取得できます。
XCUIElementTypeQueryProvider からの取得には、buttons を使用します。
Button を取得
1 2 3 4 5 6 |
let app = XCUIApplication() app.launch() let button = app.buttons["MyButton"] |
状態のチェック
Button に使用されているテキストは、label から取得できます。
操作
Button に対して、tap() 等を指定することもできます。
テストコード
以下では、TestButton という accessibility ID を付与した Button に対して、tap した後に、表示されているラベルをテストしています。
Image テスト例
1 2 3 4 5 6 7 8 9 10 11 12 |
// UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // (1) let button = app.buttons["AccessibilityID"] // (2) XCTAssertEqual(button.label, "Text") // (3) button.tap() |
コード解説
- AccessibilityID という ID を設定された Button を取得
- Button の ラベルをテスト
- Button を タップ
アプリとテストコード例
画面に、Button が表示され、その Button をタップすると Button のラベル が切り替わるアプリと、そのアプリ用のテストコードです。
Button アプリ
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 26 27 28 29 30 |
// // ContentView.swift // // Created by : Tomoaki Yagishita on 2020/11/08 // © 2020 SmallDeskSoftware // import SwiftUI struct ContentView: View { @State private var buttonTitle = "Hello" var body: some View { Button(action: { buttonTitle = "World!" }, label: { Text(buttonTitle) .font(.largeTitle) }) .accessibility(identifier: "TestButton") .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } |
Button アプリ テストコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
func testButton() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // (1) let button = app.buttons["TestButton"] // (2) XCTAssertEqual(button.label, "Hello") // (3) button.tap() // (4) XCTAssertEqual(button.label, "World!") } |
コード解説
- TestButton という Accessibility ID の設定された Button を取得
- ラベルが、”Hello” であることをテスト
- ボタンをタップ/クリック
- ラベルが、”World!” であることをテスト
まとめ:SwiftUI の Button をテストする方法
SwiftUI の Button をテストする方法
- XCUIApplication から、accessibility ID 指定で Button を取得する
- tap() 等の動作は、他の要素と同様
- 表示している ラベル は、label から名称を取得できる
説明は以上です。
不明な点やおかしな点ありましたら、ご連絡いただけるとありがたいです。
Sponsor Link