Tuesday, 15 July 2014

android - How to test a ListActivity by mocking its contentProvider and thus isolate test from database? -



android - How to test a ListActivity by mocking its contentProvider and thus isolate test from database? -

i have listview activity loads info asynchronously sqlite database using contentprovider. want test activity don't want utilize database. because want repeatable.

i'm trying mock content provider way:

public class mockrecipecontentprovider extends mockcontentprovider{ private list<hashmap<string, string>> results; @suppresswarnings("nls") public mockrecipecontentprovider(){ super(); this.results = new arraylist<hashmap<string,string>>(); //..populate this.result som info } @override public cursor query(uri uri, string[] projection, string selection, string[] selectionargs, string sortorder) { matrixcursor mcursor = new matrixcursor(new string[] {recipetable.column_id, recipetable.column_name, recipetable.column_ingredients, recipetable.column_directions}); for(int =0; i<this.results.size(); i++){ mcursor.addrow(this.getdataatposition(i)); } homecoming mcursor; } }

and test case:

public class mainactivitytest extends activityunittestcase<mainactivity>{ private static final int initial_num_items = 2; private mainactivity mactivity; public mainactivitytest() { super(mainactivity.class); } @override public void setup() throws exception{ super.setup(); final mockcontentresolver mockresolver = new mockcontentresolver(); mockrecipecontentprovider mockcontentprovider = new mockrecipecontentprovider(); mockresolver.addprovider(recipecontentprovided.authority, mockcontentprovider); contextwrapper mactivitycontext = new contextwrapper( getinstrumentation().gettargetcontext()) { @override public contentresolver getcontentresolver() { homecoming mockresolver; } }; this.setactivitycontext(mactivitycontext); startactivity(new intent(mactivitycontext, mainactivity.class), null, null); this.mactivity = getactivity(); } public void testdisplaycorrectnumofitems(){ listview lv = this.mactivity.getlistview(); asserttrue(lv.getcount()==initial_num_items); } }

the problem mockrecipecontentprovider.query() not called, neither recipecontentprovider.query(), listview not populate. doing wrong?

on other hand, write integration test case, extending activityinstrumentationtestcase2, test life cycle etc, i've read mocking not possible if extending activityinstrumentationtestcase2. so, how can code test without relaying on database?

i don't want utilize database because think although utilize renamingdelegatingcontext cause tests wouldn't repeatable @ all, unless drop test database , recreate in setup() method. done?

android unit-testing android-testing android-mockup

No comments:

Post a Comment