简体   繁体   中英

How can a SearchView in the ActionBar be tested?

I can't find any examples or help in the JavaDocs on how to use an Android test to get at the SearchView in the Menu for testing. Is there a way to do it?

I would like to do do a .setQuery("Foo", true) or equivalent to test search in my app. How can that be done?

According to this documentation

Note: Although collapsing your action view is optional, we recommend that you always collapse your action view if it includes SearchView. Also be aware that some devices provide a dedicated SEARCH button and you should expand your search action view if the user presses the SEARCH button. Simply override your activity's onKeyUp() callback method, listen for the KEYCODE_SEARCH event, then call expandActionView().

If you have expanded the serach view for the KEYCODE_SEARCH event,then testing should be possible by using the instrumentation to inject events.

public void testSearch() { 
   Instrumentation instrumentation = getInstrumentation(); 
   instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_SEARCH); 
   instrumentation.sendCharacterSync(KeyEvent.KEYCODE_F); 
   instrumentation.sendCharacterSync(KeyEvent.KEYCODE_O); 
   instrumentation.sendCharacterSync(KeyEvent.KEYCODE_O);
   //Assert here for whatever you want. 
}

Make sure you have the inject permission in your manifest.

我认为你可以使用monkeyrunner来做到这一点: http//developer.android.com/tools/help/monkeyrunner_concepts.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM