LoginSignup
0
1

More than 1 year has passed since last update.

【SwiftUI】 UITest触ってみる。

Last updated at Posted at 2022-09-11

簡単なUITestの書き方メモです。

ボタン(Button)、テキストラベル(Text)、テキストフィールド(Textfield)、
それぞれの表示内容を取得してチェックする簡単なテストを作成しました。

(ちょっとmacOSでアプリ作ってみたい欲があるので、
プロジェクトはmacOS用で作成しています。
下記コードはiOS用でもほぼ同じ内容で動作すると思いますが)

開発環境

MacOS Monterey 12.2.1
Xcode Version 13.4.1
Swift Version 5

テスト用の画面

import SwiftUI

struct ContentView: View {
  @State private var buttonTitle = "Hello"
  @State private var textEditTest = ""
  @State private var textEditTest2 = ""
  var body: some View {
    VStack {
      HStack {
        Text("TEXT_1:")
          .padding()
        Text(buttonTitle)
          .accessibility(identifier: "TestText")
          .padding()
      }
      HStack {
        Text("TEXT_2:")
          .padding()
        Text(textEditTest2)
          .accessibility(identifier: "TestText2")
          .padding()
      }
      TextField(
        "testTextField",
        text: $textEditTest
      )
        .accessibility(identifier: "TestTextField")
        .frame(width: 200)
      Button(buttonTitle) {
        // ボタンの表示を変更
        buttonTitle = "World"
        // textFieldの値をtextに設定
        textEditTest2 = textEditTest
      }
        .accessibility(identifier: "TestButton")
        .padding()
    }
    .frame(
      width: 600,
      height: 600)
  }
}

画面レイアウト

スクリーンショット 2022-09-11 19.03.24.png

UITestsのコード(追加部分のみ抜粋)

  override func setUpWithError() throws {
      super.setUp()
      // とりあえずテストを最後まで流す。
      continueAfterFailure = true
      XCUIApplication().launch()
  }

  func testButton() throws {
    // UI tests must launch the application that they test.
    let app = XCUIApplication()
    let button = app.buttons["TestButton"]
    let text = app.staticTexts["TestText"]
    let text2 = app.staticTexts["TestText2"]
    let textfield = app.textFields["TestTextField"]
    // (1)
    // Textの表示内容はvalueで取る
    XCTAssertEqual(text.value as! String, "Hello")
    // (2)
    // Buttonの表示内容はtitleで取る
    XCTAssertEqual(button.title, "Hello")
    // (3)
    textfield.typeText("テスト")
    // (4)
    button.tap()
    // (5)
    XCTAssertEqual(button.title, "World")
    // (6)
    // TextFieldの入力内容はvalueで取る
    XCTAssertEqual(textfield.value as! String, text2.value as! String)
  }

注意点

ネットで調べた関連の記事では .labelで値が取得できるとなっているものがあったり、
書き方がちょっと変わっていってるのかな、という印象です。
今後のアップデートの注視が必要そう。

コード全文

コード全文は以下を参照ください。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1