LoginSignup
4
7

More than 3 years have passed since last update.

【XCUITest】UITextFieldの値の削除と入力(iPadOS13/Xcode11対応)

Last updated at Posted at 2019-12-03

はじめに

iOSアプリ開発でXCUITestを実装しており、その際に、「UITextFieldの値を削除し、そこに新しい値を入力する」という処理が必要になりました。
stack overflowのこちらの記事( UI Test deleting text in text field )を参考に、XCUIElementのExtensionでclearAndEnterTextを作成することでiOS12(Xcode10)では期待通り動いていたのですが、iPadOS13(Xcode11)に上げてからUITextFieldの値が削除されなくなってしまったので、その対応を行いました。その対応方法を記載します。

前提

  • Xcode Version 11.2
  • iPadOS13

iOS12(Xcode10)では期待通りに動いていたclearAndEnterText

UI Test deleting text in text field からclearAndEnterTextのコードを抜粋します。
UITextFieldをタップすることで、カーソル位置が入力されている値の最後尾に来るので、そこからdeleteStringを文字数分入力することで値を削除しています。


extension XCUIElement {
    /**
     Removes any current text in the field before typing in the new value
     - Parameter text: the text to enter into the field
     */
    func clearAndEnterText(text: String) {
        guard let stringValue = self.value as? String else {
            XCTFail("Tried to clear and enter text into a non string value")
            return
        }

        self.tap()

        let deleteString = String(repeating: XCUIKeyboardKey.delete.rawValue, count: stringValue.count)

        self.typeText(deleteString)
        self.typeText(text)
    }
}

iPadOS13(Xcode11)でUITextFieldの値が削除されなくなってしまった原因

Xcode11から、UITextFieldをタップするとカーソル位置が入力されている値の先頭に移動するようになり、deleteStringを入力しても1文字も消えなくなっていました。

iPadOS13(Xcode11)対応のために修正したclearAndEnterText

UITextFieldをダブルタップすることで、テキストを全選択し、deleteStringを1度入力することで値を削除するようにしてみました。


extension XCUIElement {
    /**
     Removes any current text in the field before typing in the new value
     - Parameter text: the text to enter into the field
     */
    func clearAndEnterText(text: String) {
        // ダブルタップでテキストを全選択
        self.doubleTap()

        // deleteは1回のみ 
        let deleteString = String(repeating: XCUIKeyboardKey.delete.rawValue, count: 1)

        self.typeText(deleteString)
        self.typeText(text)
    }
}

おわりに

他にも対応方法はあると思いますが、私のケースではこの方法で期待通りにテストできるようになったので、一旦これで良しとしています。

参考

4
7
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
4
7