How to check ListActivity by making fun of its contentProvider and thereby isolate the test from the database?

I have a ListView function that asynchronously loads its data from an SQLite database using ContentProvider. I want to verify this action, but I do not want to use the database. Because I want it to be repeated.

I am trying to make fun of my content provider in this 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 with som data
}

@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 i =0; i<this.results.size(); i++){
        mCursor.addRow(this.getDataAtPosition(i));
    }
    return mCursor;
}
}       

And this is my 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() {
            return 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 is that MockRecipeContentProvider.query () is not called, not RecipeContentProvider.query (), so the listView is not populated. What am I doing wrong?

, , ActivityInstrumentationTestCase2, .., , , ActivityInstrumentationTestCase2. , ?

, , , RenamingDelegatingContext, , , setUp (). ?

+4

Source: https://habr.com/ru/post/1545126/


All Articles