在測試自動化的過程中,有時經常需要獲取Toast的String來作檢驗。
在robotium中,我們知道可以通過solo.getView("message")方法獲取Toast的TextView,然後得到其String值,那麼其內部是怎麼實現的呢。
首先看下我們一般是怎麼調用Toast的:
Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
當應用中調用Toast的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;
}
由上可知,調用makeText時,系統初始化了個TextView,且這個TextView的id系統的id,爲:com.android.internal.R.id.message知道了Toast的本質是一個TextView,且其id是com.android.internal.R.id.message後,要獲取它的String就好辦了。
看robotium中的getView()方法的實現:
/**
* Returns a {@code View} with a given id.
*
* @param id the id of the {@link View} to return
* @param index the index of the {@link View}. {@code 0} if only one is available
* @return a {@code View} with a given id
*/
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);
}
robotium爲了方便以String形式的id來查找控件,因此封裝了個如上getView(String id, int index)通過String id來獲取View的方法,在這個方法中通過getIdentifier把String形式的id轉變成int型的id,然後再根據Int型的id來查找控件,由上文我們已經知道Toast的id了,因此我們可以簡單地通過solo.getView("message")來獲取Toast的TextView。
當然了,爲了實際項目中能更好地獲取Toast,我們可以自己再封裝一下:
/**
* 獲取Toast的String值
* @return
*/
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;
}
好吧,天冷又水了一篇。。