Testing database on Android: ProviderTestCase2 or RenamingDelegatingContext?

后端 未结 5 2042
[愿得一人]
[愿得一人] 2020-12-13 04:14

I\'ve implemented access to a database using SQLiteOpenHelper from the android.database package within some classes (with pattern DAO).

I wrote some jun

5条回答
  •  执笔经年
    2020-12-13 05:11

    I have an application that uses a ContentProvider backed by an sqlite database to provide data to the application.

    Let PodcastDataProvider be the actual dataprovider used by the application.

    Then you can set up a test provider with something like the following:

    public abstract class AbstractPodcastDataProvider extends ProviderTestCase2{
        public AbstractPodcastDataProvider(){
            this(PodcastDataProvider.class, Feed.BASE_AUTH);
        }
    
        public AbstractPodcastDataProvider(Class providerClass,
                String providerAuthority) {
            super(providerClass, providerAuthority);
        }
    
        public void setUp() throws Exception{
            super.setUp();
    
            //clear out all the old data.
            PodcastDataProvider dataProvider = 
                (PodcastDataProvider)getMockContentResolver()
                .acquireContentProviderClient(Feed.BASE_AUTH)
                .getLocalContentProvider();
            dataProvider.deleteAll();
        }
    }
    

    to setup a test data provider that will be backed by a different database than the actual application.

    To test the DAO, create another class which extends AbstractPodcastDataProvider and use the

    getMockContentResolver();
    

    method to get an instance of a content resolver that will use the test database instead of the application database.

提交回复
热议问题