简体   繁体   English

带有 API 级别 28 的 Android-ProviderTestCase2 不起作用

[英]Android-ProviderTestCase2 with API Level 28 not working

Some time ago I created some instrumented tests using ProviderTestCase2.前段时间我使用 ProviderTestCase2 创建了一些仪器测试。 Now I wanted to update my codebase and tried to reactivate my old tests in the current environment.现在我想更新我的代码库并尝试在当前环境中重新激活我的旧测试。

1) When I update to compileSdkVersion 28 there seems to be no class ProviderTestCase2 any more. 1) 当我更新到 compileSdkVersion 28 时,似乎不再有 ProviderTestCase2 类了。 Cleaning and building the Project failed.清理和构建项目失败。 If I go back to version 27 I can successfully build the project.如果我回到版本 27,我可以成功构建项目。

2) I have a special case where I want to test different variants of an object with a set of tests. 2)我有一个特殊情况,我想用一组测试来测试一个对象的不同变体。 So I decided to make use of inheritance and placed the tests in the base class, configuring the objects to be tested by the superclass.所以我决定利用继承并将测试放在基类中,配置超类要测试的对象。 This had worked in the past.这在过去曾奏效。 (Yes, I know about opinions that inheritance in tests is bad, but in this case it is OK ;-) ) (是的,我知道测试中的继承是不好的,但在这种情况下是可以的;-))

Now no tests are executed.现在不执行任何测试。 Android Studio complains that there is an empty test suite. Android Studio 抱怨有一个空的测试套件。

Also there are warnings that I have tests with JUnit4 Annotations in a class extending JUnit3.还有警告说我在扩展 JUnit3 的类中使用 JUnit4 注释进行了测试。 I do not remember that I saw these warnings in the past.我不记得我过去看到过这些警告。

Is this a bug in the Android Libraries?这是 Android 库中的错误吗? Or where can I find some hints how to solve this problem?或者我在哪里可以找到一些如何解决这个问题的提示?

(Using Android Studio 3.2 and the currentmost libraries) (使用 Android Studio 3.2 和最新的库)

The ProviderTestCase2 was removed . ProviderTestCase2已删除 The ProviderTestRule should be used instead (from support test library or AndroidX).应该使用ProviderTestRule (来自支持测试库或 AndroidX)。

See:看:

Add the com.android.support.test:rules dependency, to be able to use the rule.添加com.android.support.test:rules依赖项,以便能够使用规则。

Here is an example from the reference page:这是参考页面中的示例:

@Rule
public ProviderTestRule mProviderRule =
    new ProviderTestRule.Builder(MyContentProvider.class, MyContentProvider.AUTHORITY).build();

@Test
public void verifyContentProviderContractWorks() {
    ContentResolver resolver = mProviderRule.getResolver();
    // perform some database (or other) operations
    Uri uri = resolver.insert(testUrl, testContentValues);
    // perform some assertions on the resulting URI
    assertNotNull(uri);
}

The accepted answer is not correct.接受的答案不正确。 ProviderTestRule being in Beta, there is no deprecation or removal of ProviderTestCase2 . ProviderTestRule处于测试阶段,没有弃用或删除ProviderTestCase2 What happened is that is has been moved to a library that you need to declare in your build.gradle :发生的事情是它已移至您需要在build.gradle声明的build.gradle

useLibrary 'android.test.base'

See: https://developer.android.com/training/testing/set-up-project请参阅: https : //developer.android.com/training/testing/set-up-project

TLDR TLDR

build.gradle : build.gradle

android {    
  useLibrary 'android.test.base' // for AndroidTestCase
  useLibrary 'android.test.runner' // for ProviderTestCase2
  useLibrary 'android.test.mock' // for MockContentProvider
}

Android documentation about various JUnit -based libraries available with the useLibrary call: https://developer.android.com/training/testing/set-up-project#junit-based-libs有关可通过useLibrary调用获得的各种基于JUnit的库的 Android 文档: https : //developer.android.com/training/testing/set-up-project#junit-based-libs

Further Explanation进一步说明

mtotschnig's answer is on the right track, but it isn't complete. mtotschnig 的答案在正确的轨道上,但并不完整。

First, to import ProviderTestCase2 , you need首先,要导入ProviderTestCase2 ,您需要

build.gradle : build.gradle

android {
  useLibrary 'android.test.runner'
}

However, ProviderTestCase2 extends AndroidTestCase , so you'll then need:但是, ProviderTestCase2扩展了AndroidTestCase ,因此您需要:

build.gradle : build.gradle

android {
  useLibrary 'android.test.base'
}

Finally, if you're extending ProviderTestCase2 , you need to provide a type extending ContentProvider , and you may need to extend MockContentProvider to create it.最后,如果您要扩展ProviderTestCase2 ,您需要提供一个扩展ContentProvider的类型,并且您可能需要扩展MockContentProvider来创建它。 For MockContentProvider , you need ( thanks to Sienna's related answer ):对于MockContentProvider ,您需要(感谢 Sienna 的相关答案):

build.gradle : build.gradle

android {
  useLibrary 'android.test.mock'
}

Tried ProviderTestRule many times to test my custom ContentProvider class but succeeded only when add my Test class to androidTest folder, here is the example kotlin code :多次尝试ProviderTestRule来测试我的自定义ContentProvider类,但仅在将我的 Test 类添加到androidTest文件夹时才成功,这是示例kotlin代码:

    //this is my custom provider class    
    public final class NameProvider : ContentProvider() {
        private var pContext: Context? = null;
        private var nameDbHelper: NameDbHelper? = null
        private var dataBase: SQLiteDatabase? = null
        private val Log_Tag = "NAME_PROVIDER"
        
        override fun onCreate(): Boolean {
            pContext = context
            nameDbHelper = pContext?.let { NameDbHelper(it) }
            dataBase = nameDbHelper?.writableDatabase
            if (dataBase == null) {
                Log.d(Log_Tag, "dataBase NOT created ...")
                return false
            }
            Log.d(Log_Tag, "dataBase created ...")
            return true
        }
    
        override fun query(p0: Uri, p1: Array<out String>?, p2: String?, p3: Array<out String>?, p4: String?): Cursor? {
            var queryBuilder : SQLiteQueryBuilder = SQLiteQueryBuilder()
            queryBuilder.tables = "TABLE_NAME"
            val cursor = queryBuilder.query(dataBase,p1,p2,p3,null,null, "COLUMN_NAME")
            cursor.setNotificationUri(pContext?.contentResolver, p0)
            return cursor
        }
    
        override fun insert(p0: Uri, p1: ContentValues?): Uri? {
            val rowID: Long? = dataBase?.insert("TABLE_NAME", "", p1)
            rowID?.let {
                if (it > 0) {
                    val _uri = ContentUris.withAppendedId(CONTENT_URI, it)
                    pContext?.contentResolver?.notifyChange(_uri, null)
                    return _uri
                }
            }
            throw SQLException("Failed to add a record into")
        }
        
        override fun getType(p0: Uri): String? {
            TODO("Not yet implemented")
        }
    
        override fun delete(p0: Uri, p1: String?, p2: Array<out String>?): Int {
            TODO("Not yet implemented")
        }
    
        override fun update(p0: Uri, p1: ContentValues?, p2: String?, p3: Array<out String>?): Int {
            TODO("Not yet implemented")
        }
    }

Now the test class that I can run successfully :现在我可以成功运行的测试类:

    @RunWith(AndroidJUnit4::class)
    class NameProviderTest {
        @get:Rule
        var mProviderRule = ProviderTestRule.Builder(NameProvider::class.java, NameContract.AUTHORITY)
                .setDatabaseCommands(NameContract.DATABASE_NAME).build()
    
        @Test
        fun contentResolverNull(){
            val resolver = mProviderRule.resolver
            assertNotNull(resolver)
        }

        @Test
        fun query() {
            val cursor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mProviderRule.resolver.query(NameContract.CONTENT_URI, null, null, null)
            } else {
                null
            }
            assertNotNull(cursor)
            var name : String? = null
            if(cursor != null && cursor.moveToFirst()){
                name = cursor.getString(cursor.getColumnIndex(NameContract.KEY_NAME))
            }
            assertNotNull(name)
            assertEquals(name, "Taher")
        }
    
        @Test
        fun insert() {
            val values =  ContentValues()
            values.put(NameContract.KEY_NAME, "Taher");
            val uri = mProviderRule.resolver.insert(NameContract.CONTENT_URI, values);
            assertNotNull(uri)
        }
    }

Better Approach更好的方法

But then I have found a better way to do this by using robolectric:4.2 .但是后来我找到了一种更好的方法来使用robolectric:4.2来做到这一点。 This time it feels like actual unit test as I can do this by adding my Test class NameProviderTest to the test folder.这一次感觉就像是实际的单元测试,因为我可以通过将我的测试类 NameProviderTest 添加到测试文件夹来做到这一点。

Now the test class look like this:现在测试类看起来像这样:

    @Config(maxSdk = 29)
    @RunWith(RobolectricTestRunner::class)
    class NameProviderTest {
    
        private var contentResolver : ContentResolver? = null
        private var shadowContentResolver : ShadowContentResolver? = null
        private var nameProvider : NameProvider? = null
        
        @Before
        fun setUp() {
            contentResolver = ApplicationProvider.getApplicationContext<Context>().contentResolver
            val providerInfo : ProviderInfo = ProviderInfo()
            providerInfo.authority = NameContract.AUTHORITY
            providerInfo.grantUriPermissions = true
            val controller = Robolectric.buildContentProvider(NameProvider::class.java).create(providerInfo)
            shadowContentResolver = shadowOf(contentResolver)
            nameProvider = controller.get()
    
        }
    
        @Test
        fun onCreate() {
            val res  = nameProvider?.onCreate()
            assertEquals(res, true)
            //ShadowContentResolver.registerProviderInternal(NameContract.AUTHORITY, nameProvider)
        }
    
        @Test
        fun query() {
            val values =  ContentValues()
            values.put(NameContract.KEY_NAME, "ABCD");
            val uri = contentResolver?.insert(NameContract.CONTENT_URI, values);
            assertNotNull(uri)
            val cursor = contentResolver?.query(NameContract.CONTENT_URI,null,null,null,null)
            assertNotNull(cursor)
            var name : String? = null
            if(cursor != null && cursor.moveToFirst()){
                name = cursor.getString(cursor.getColumnIndex(NameContract.KEY_NAME))
            }
            cursor?.close()
            assertNotNull(name)
            assertEquals(name, "ABCD")
        }
        
        @Test
        fun insert() {
            val values =  ContentValues()
            values.put(NameContract.KEY_NAME, "Taher");
            val uri = contentResolver?.insert(NameContract.CONTENT_URI, values);
            assertNotNull(uri)
    
        }
    
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Socket.io 不适用于 Android 9(API 级别 28) - Socket.io not working on Android 9 (API level 28) 运行时权限在 API 级别 28 中不起作用 - Run time permission not working from API Level 28 获取Android位图字节数i(API级别18-28) - Get Android Bitmap Byte Count i (API level 18 - 28) Java Android getContentResolver().query 特定Camera 文件夹以在Android API 级别&lt;= 28 个设备中获取光标 - Java Android getContentResolver().query for specific Camera folder to get cursor in Android API level <= 28 devices android studio和最新sdk版本的API级别为28,appcompat-v7文件夹中的API级别为26.0.0-alpha1 - API level of 28 in android studio and latest sdk-version is 26.0.0-alpha1 in appcompat-v7 folder Android 9 Api 28 通知未显示 - Android 9 Api 28 Notification not showing Broadcastreceiver无法在android Nougat API 25级中工作吗? - Broadcastreceiver not working in android Nougat api level 25? 如何修复API 28中的Android数据绑定错误? - How to fix Android Databinding Error in API 28? fromHtml方法在API级别28上无法正确格式化html文本 - fromHtml method does not format html text properly on API level 28 前台服务在 Android 9 (API 28) 中不起作用 - Foreground Service doesnt work in Android 9 (API 28)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM