branch10480’s blog

Topics that I've learned.

iOSアプリ開発自動テストの教科書 を読んでいく 〜 18 〜

UIテスト実装に向けて以下の手順について知る。

項目
UI要素の特定方法
UI要素の操作方法
UI要素の属性や状態の確認方法

UI要素の特定方法

XCUIElementQuery というクラスのクエリで対象となるUI要素(XCUIElement)を検索する。

import XCTest
import UIKit

class SampleTestCases: XCTestCase {
    func testExample() {
        let app = XCUIApplication()

        // 表示されている画面上の全てのボタン
        let allButtons = app.descendants(matching: .button)
        // 'sample_button'というアクセシビリティ識別子が設定されているボタン
        let specificButton = allButtons.matching(identifier: "sample_button").element
    }
}

アクセシビリティ識別子には Label や Identifier があるが、Identifier を利用した方が良い(Labelはローカライズによって環境で値が変わる)。

UIを特定するための要素としては 表示されている文字列場所 が使える。

import XCTest
import UIKit

class SampleTestCases: XCTestCase {
    func testExample() {
        let app = XCUIApplication()

        // Accessibility Identifierを使用したケース
        let byUsingIdentification = app.textFields["hoge_id"]
        // 表示されている文字列を使用したケース
        let useValueButton = app.textFields["email"]
    }
}

UI要素を操作

XCUIElement のメソッドを使って操作する。

import XCTest
import UIKit

class SampleTestCases: XCTestCase {
    func testExample() {
        let app = XCUIApplication()

        let loginEmailTextField = app.textFields["login_email_textfield"]
        // これを入れないと次が失敗する
        // TextFieldにフォーカスを当てる必要がある
        loginEmailTextField.tap()
        
        // テキスト入力
        loginEmailTextField.typeText("user@example.com")
    }
}

UI要素の属性を確認する

import XCTest
import UIKit

class SampleTestCases: XCTestCase {
    func testExample() {
        let app = XCUIApplication()

        // get elements
        let emailTextField = app.textFields["email_textfield"]
        let passwordTextField = app.textFields["password_textfield"]
        let loginButton = app.buttons["login_button"]

        emailTextField.tap()
        emailTextField.typeText("sample@mail.com")

        passwordTextField.tap()
        passwordTextField.typeText("pass")

        loginButton.tap()

        // check properties
        let emailLabel = app.staticTexts["user_email_label"].label
        XCTAssertEqual(emailLabel, "sample@mail.com")
    }
}

> 次回に続く