[英]Is there the ability to unit test a MaterialSearchBar on Android Studio?
我一直在對我的代碼進行單元測試,並且一直在努力尋找一種方法來從implementation 'com.github.mancj:MaterialSearchBar:+'
Android Studio 上對 MaterialSearchBar 進行單元測試。
我試圖通過鍵入來對其進行單元測試
@Test
public void searchForTony() {
onView(withId(R.id.search_bar)).perform(click()).perform(typeText("Tony"));
}
但這似乎不起作用,這類似於我對 EditText 字段進行單元測試的方式,我可以請我就如何處理這個問題提供一些指導嗎?
謝謝
MaterialSearchBar
是ViewGroup
而不是EditText
,因此您將無法直接使用perform(typeText("Tony"))
。 但是您知道它只包含一個EditText
。
您可以通過在EditText
上使用另一個ViewMatcher
來找到EditText
:
@Test
public void findEditTextByClassName(){
onView(withClassName(containsString(EditText.class.getSimpleName()))).perform(replaceText("Tony"));
onView(withText("Tony")).check(matches(isDisplayed()));
}
或者,您可以搜索View
樹,從MaterialSearchBar
作為根目錄開始,因為您知道它在布局中出現在哪個 id 下:
@Test
public void findEditTextInViewTree(){
// NOTE exchange R.id.material_search_bar for your own id value!
ViewGroup viewGroup = activityRule.getActivity().findViewById(R.id.material_search_bar);
int id = -1;
for(int i = 0; i < viewGroup.getChildCount(); i++){
View view = viewGroup.getChildAt(i);
if(view instanceof EditText){
id = view.getId();
}
}
onView(allOf(withParent(withId(R.id.material_search_bar)),withId(id))).perform(replaceText("Tony"));
onView(withText("Tony")).check(matches(isDisplayed()));
}
請注意,我使用的是replaceText()
而不是typeText()
因為這篇文章是關於查找View
,而不是等待typeText()
完成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.