ContentProvider测试 - 分离生产和测试数据

时间:2017-01-14 20:11:22

标签: android unit-testing testing android-contentprovider

我已经开始为我的内容提供商编写一个简单的测试。问题是当我运行测试时它正在使用生产数据。如何确保从我的实时应用数据中使用单独的测试数据?

@RunWith(AndroidJUnit4.class)
public class MyContentProviderTest extends ProviderTestCase2<MyContentProvider>{
    public MyContentProviderTest() {
        super(MyContentProvider.class, MyContentProvider.AUTHORITY);
    }

    @Override
    protected void setUp() throws Exception {
        setContext(InstrumentationRegistry.getContext());
        //have also tried with setContext(InstrumentationRegistry.getTargetContext());
        super.setUp();
    }

    @Test
    public void insertTest(){
        ContentResolver contentResolver = getContext().getContentResolver();
        assertNotNull(contentResolver);

        contentResolver.insert(MyContentProvider.uri,createContentValues());
        Cursor cursor = contentResolver.query(MyContentProvider.uri, Database.ALL_COLUMNS,
             null, null, null);

        assertNotNull(cursor);

        // the test fails here because along with the row inserted above, there are also many more rows of data from using my app normally (not while under test).
        assertEquals( 1, cursor.getCount());

        //todo: verify cursor contents
        cursor.close();
    }

    ContentValues createContentValues(){
        ContentValues cv = new ContentValues();
        cv.put(Database.COLUMN_DATETIME, LocalDateTime.now().format(Util.DATE_FORMAT));
            /* ... etc */
        return cv;
    }
}

1 个答案:

答案 0 :(得分:1)

  

我应该使用不同的URI吗?

是。您的测试代码正在影响您的生产提供商。您需要测试代码才能访问单独的测试提供程序,并且需要自己的权限字符串(并且从那里Uri)。

新应用开发的典型方法是从applicationId

生成权限字符串
<provider
    android:name="MyContentProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true" />

用于Uri构建的Java的权限字符串变为BuildConfig.APPLICATION_ID+".provider"。这要求您将Gradle用于构建(例如,通过Android Studio),或者在您正在使用的任何构建系统中使用等效工具。

您的测试代码将获得a separate testApplicationId automatically,或者您可以根据需要在Gradle中覆盖它。为生产与测试分别提供单独的应用程序ID意味着您拥有单独的内部存储,并且您的代码始终引用正确的提供程序(通过特定于应用程序ID的权限)意味着您的测试代码将使用测试提供程序和测试构建内部存储,您的生产代码将使用生产提供程序和生产构建的内部存储。