Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

UI 自動化測試中如何抓取 Toast 的文字內容

編輯:關於 Android 程式設計

做 UI 自動化測試時,Toast 提示經常是唯一的驗證依據——「再按一次退出程式」「網路連線失敗」這類訊息不會留在畫面上,卻是判斷流程是否正確的關鍵。Robotium 提供了 solo.getView("message") 來取得它,但要理解為什麼這樣能work,得先知道 Toast 到底是什麼。

Toast 的本質是一個 TextView

我們平常這樣呼叫:

Toast.makeText(getApplicationContext(), "再按一次退出程式", Toast.LENGTH_SHORT).show();

走進 makeText 的實作:

public static Toast makeText(Context context, CharSequence text, int duration) {
    Toast result = new Toast(context);
    LayoutInflater inflate = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
    TextView tv = (TextView) v.findViewById(com.android.internal.R.id.message);
    tv.setText(text);
    result.mNextView = v;
    result.mDuration = duration;
    return result;
}

結論很清楚:系統會 inflate 一個名為 transient_notification 的佈局,其中的 TextView 擁有固定的系統 ID com.android.internal.R.id.message。也就是說,所有 Toast 的文字都掛在一個 id 為 message 的 TextView 上。知道這件事,抓取它只是資源查詢的問題。

Robotium 的 getView 怎麼運作

/**
 * 以字串形式的 id 取得 View
 *
 * @param id    View 的 id 名稱
 * @param index 同名 View 的序號,只有一個時傳 0
 */
public View getView(String id, int index) {
    View viewToReturn = null;
    Context targetContext = instrumentation.getTargetContext();
    String packageName = targetContext.getPackageName();

    // 先在受測程式的資源中查
    int viewId = targetContext.getResources().getIdentifier(id, "id", packageName);
    if (viewId != 0) {
        viewToReturn = getView(viewId, index, TIMEOUT);
    }

    // 找不到再去系統資源中查
    if (viewToReturn == null) {
        int androidViewId =
                targetContext.getResources().getIdentifier(id, "id", "android");
        if (androidViewId != 0) {
            viewToReturn = getView(androidViewId, index, TIMEOUT);
        }
    }

    if (viewToReturn != null) {
        return viewToReturn;
    }
    return getView(viewId, index);
}

關鍵就是 getIdentifier(id, "id", packageName) 把字串形式的名稱轉成 int 型資源 ID,再用該 ID 去查找控制項。第二段查詢把套件名換成 android,正好對應 Toast 所在的系統資源,所以 solo.getView("message") 才能取到那個 TextView。

封裝一個更好用的方法

直接呼叫有個問題:Toast 是異步顯示的,呼叫 show() 之後畫面上未必立刻就有它,而消失得也很快。實務上需要一個帶超時的輪詢:

/**
 * 取得 Toast 的文字內容
 *
 * @param timeout 最長等待毫秒數
 */
public String getToast(int timeout) {
    TextView toastTextView = null;
    String toastText = "";
    long endTime = SystemClock.uptimeMillis() + timeout;

    while (SystemClock.uptimeMillis() < endTime) {
        toastTextView = (TextView) getView("message", 0);
        if (null != toastTextView) {
            toastText = toastTextView.getText().toString();
            break;
        } else {
            sleeper.sleepMini();   // 短暫休眠後重試
        }
    }
    return toastText;
}

這裡用 SystemClock.uptimeMillis() 而不是 currentTimeMillis(),是因為前者不受系統時間調整影響,比較適合計算逾時。

換成其他工具時怎麼做

如果專案不用 Robotium,思路完全一致,只是 API 不同:

  • UiAutomator2 / Espresso:Toast 屬於系統層級的浮層,通常需要用 UiDevice 的 findObject(By.textContains(...)) 搭配 wait 來等待,或用 UiAutomator 的 UiObject2 查詢 resource-id="android:id/message"。
  • 直接寫 adb 指令:透過 uiautomator dump 匯出當前 UI 樹再解析 XML,適合臨時排查。
  • 改寫成可測試的設計:最根本的做法是把提示訊息抽成常數或資源字串,測試端直接比對同一份來源,不必依賴解析畫面。

需要留意的是,Toast 的顯示時間只有 2 秒或 3.5 秒(由系統的 SHORT_DELAY/LONG_DELAY 決定),加上不同 ROM 對浮層的繪製策略差異,抓取失敗率天生不低。因此這種斷言最好只用在關鍵路徑上,並為它設計合理的重試機制,而不是拿來驗證每一個提示。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved