开发者

How can I automate a test that sends multiple mock intents to an Android activity?

开发者 https://www.devze.com 2023-02-27 01:27 出处:网络
I am trying to send mock intents to an Android activity via the Android instrumentation tools and Android JUnit in Eclip开发者_开发技巧se.

I am trying to send mock intents to an Android activity via the Android instrumentation tools and Android JUnit in Eclip开发者_开发技巧se.

I am able to successfully create a test that sends one Intent to an Activity, but I want to automate this and send several consecutive Intents so I can test the Activity with many pieces of data put in as an "extra" in the Intent. My code (which works for a single Intent) is as follows:

public class SearchTest extends ActivityInstrumentationTestCase2<SearchResults> {

    private ListActivity mActivity;
    private ArrayList<String> testManifest = new ArrayList<String>();
    TextView tv; 


    public SearchTest() {
        super("org.fdroid.fdroid", SearchResults.class);
    }//SearchTest

    @Override
    protected void setUp() throws Exception{
        setUpTestManifest();
        super.setUp();
        setActivityInitialTouchMode(false);
        Intent i = new Intent(Intent.ACTION_SEARCH);
        i.setClassName("org.fdroid.fdroid", "org.fdroid.fdroid.SearchResults");
        i.putExtra(SearchManager.QUERY, testManifest.get(0));
        setActivityIntent(i);
        mActivity = getActivity();
        tv = (TextView) mActivity.findViewById(R.id.description);
    }//setUp

    public void testSearchResult(){
        assertTrue(mActivity.getListView().getCount() > 0);
    }//testSearchResult

    public void setUpTestManifest(){
        //populate the test manifest
        testManifest.add("Sample Key Word 1");
        testManifest.add("Sample Key Word 2");
        testManifest.add("Sample Key Word 3");
    }//setupManifest

}//SearchTest 

How can I make this work where I can have hundreds of items in the testManifest and create an Intent and test for each of those items?


Have you tried pulling out the launching of the activity out of the setUp code and into a loop within your test method? Example,

protected void setUp() {
    setUpTestManifest();
    super.setUp();
} 

public void testSearchResult(){
    for (String query : testManifest) {
        setActivityInitialTouchMode(false);
        Intent i = new Intent(Intent.ACTION_SEARCH);
        i.setClassName("org.fdroid.fdroid", "org.fdroid.fdroid.SearchResults");
        i.putExtra(SearchManager.QUERY, query);
        setActivityIntent(i);
        mActivity = getActivity();
        tv = (TextView) mActivity.findViewById(R.id.description);
        assertTrue(mActivity.getListView().getCount() > 0);
        mActivity.finish();  // close the activity
        setActivity(null);   // forces next call of getActivity to re-open the activity
    }
}

-Dan

0

精彩评论

暂无评论...
验证码 换一张
取 消