【问题标题】:ContentProvider testing - separating production and test dataContentProvider 测试 - 分离生产和测试数据
【发布时间】:2017-01-14 20:11:21
【问题描述】:

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

@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;
    }
}

【问题讨论】:

  • 我没有得到你想要归档的内容?.. 你能不能说一下应该做什么以及他们正在做什么?
  • MyContentProvider.uri是真正的生产Uri吗?
  • @CommonsWare,是的。我将它作为 MyContentProvider 的成员变量,我应该使用不同的 URI 吗?
  • @creativecreatorormaybenot 我有一个使用我的应用程序的实时数据的测试。我正在尝试了解如何在运行测试时使用单独的测试数据

标签: android unit-testing testing android-contentprovider


【解决方案1】:

我应该使用不同的 URI 吗?

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

新应用开发的典型方法是从applicationId 生成权限字符串:

<provider
    android:name="MyContentProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true" />

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

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

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 2013-08-04
    • 2016-01-23
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    相关资源
    最近更新 更多