測試內容供應器
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
如果您要實作內容供應器來儲存及擷取資料,或
讓其他應用程式存取資料。建議您測試供應商,確保
無法產生出乎意料的行為本課程說明如何公開測試
也適用於您設為不公開的
開發自己的應用程式
為內容供應器建立整合測試
內容供應器可讓您存取實際的使用者資料,因此請務必確保
在獨立的測試環境中測試內容供應器這個
可讓您只針對
測試案例這也意味著您的測試不會修改實際的使用者資料。適用對象
舉例來說,應避免編寫失敗的測試,因為有資料剩餘
來取代先前的測試同樣地,測試也應避免新增或刪除
供應商的實際聯絡資訊
如要單獨測試內容供應器,請使用 ProviderTestCase2
類別此類別可讓您使用 Android 模擬物件類別,例如
IsolatedContext
和MockContentResolver
:存取檔案並
而不影響實際使用者資料。
整合測試應以 JUnit 4 測試類別編寫。瞭解詳情
如要瞭解如何建立 JUnit 4 測試類別及使用 JUnit 4 斷言,請參閱「建立
本機單元測試類別。
如要為內容供應器建立整合測試,您必須執行
步驟:
- 將測試類別建立為
ProviderTestCase2
的子類別。
- 指定 AndroidX Test 提供的
AndroidJUnitRunner
類別
做為預設測試執行器
- 從
ApplicationProvider
類別設定 Context
物件。詳情請參閱
程式碼片段範例。
Kotlin
@Throws(Exception::class)
override fun setUp() {
super.setUp()
context = ApplicationProvider.getApplicationContext<Context>()
}
Java
@Override
protected void setUp() throws Exception {
super.setUp();
setContext(ApplicationProvider.getApplicationContext());
}
ProviderTestCase2 的運作方式
使用 ProviderTestCase2
的子類別測試提供者。此基礎類別
擴充 AndroidTestCase
,因此可提供 JUnit 測試架構
以及測試應用程式權限的 Android 專用方法。最常出現
這個類別的重要功能是初始化功能,
隔離的測試環境
初始化
初始化作業是在 ProviderTestCase2
的建構函式中完成,
而子類別則會在各自的建構函式中呼叫ProviderTestCase2
建構函式建立 IsolatedContext
物件,允許檔案和
但會在與 Android 系統的其他互動中虛設常式。
檔案和資料庫作業本身發生在
且帶有特殊的前置字元。
建構函式接著會建立 MockContentResolver
做為解析器
進行測試。
最後,建構函式會建立受測試的供應器執行個體。這是
一般 ContentProvider
物件,但會使用其所有環境
擷取 IsolatedContext
資訊,因此只有
隔離的測試環境系統會執行測試案例類別中的所有測試項目
對抗這個獨立物件
您對內容供應器執行整合測試的方式與檢測設備相同
單元測試
要測試哪些項目?
以下是關於測試內容供應器的一些具體準則。
- 使用解析器方法測試:即使你可以為提供者執行個體化
物體
在
ProviderTestCase2
中,您應一律使用
適當的 URI這麼做可確保您針對供應商測試
這種互動方式與一般應用程式所用的互動相同
- 以合約形式測試公開供應商:您想將供應商視為合約
提供給其他應用程式的公開使用,那麼您應該在合約中進行測試。
以下列舉幾個範例:
- 使用提供者公開公開的常數進行測試。舉例來說
。
這些常數一律是由供應器公開定義的常數。
- 請測試供應器提供的所有 URI。供應商可能會提供
分別參照資料的不同面向。
- 測試無效的 URI。您的單元測試應刻意呼叫
檢查內容是否有誤良好的供應商設計是擲回
IllegalArgumentException
代表無效 URI。
- 測試標準供應商互動情形:大多數供應商都提供六個存取權
方法:
query()
、insert()
、delete()
、update()
、getType()
和
onCreate()
。您的測試應確認所有這些方法都能正常運作。
- 測試商業邏輯:如果內容供應器導入商業邏輯,
你
並進行測試商業邏輯包括處理無效值、財務或
對重複項目進行算術計算、刪除或合併。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],null,["# Test content providers\n\nIf you are implementing a [content provider](/guide/topics/providers/content-providers) to store and retrieve data or to\nmake data accessible to other apps, you should test your provider to ensure that\nit doesn't behave in an unexpected way. This lesson describes how to test public\ncontent providers, and is also applicable to providers that you keep private to\nyour own app.\n\nCreate integration tests for content providers\n----------------------------------------------\n\nContent providers let you access actual user data, so it's important to ensure\nthat you test the content provider in an isolated testing environment. This\napproach allows you to only run against data dependencies set explicitly in the\ntest case. It also means that your tests do not modify actual user data. For\nexample, you should avoid writing a test that fails because there was data left\nover from a previous test. Similarly, your test should avoid adding or deleting\nactual contact information in a provider.\n| **Note:** This document focuses on [`ProviderTestCase2`](/reference/android/test/ProviderTestCase2) which is being replaced by the experimental [`ProviderTestRule`](/reference/androidx/test/rule/provider/ProviderTestRule).\n\nTo test your content provider in isolation, use the `ProviderTestCase2`\nclass. This class allows you to use Android mock object classes such as\n[`IsolatedContext`](/reference/android/test/IsolatedContext) and [`MockContentResolver`](/reference/android/test/mock/MockContentResolver) to access file and\ndatabase information without affecting the actual user data.\n\nYour integration test should be written as a JUnit 4 test class. To learn more\nabout creating JUnit 4 test classes and using JUnit 4 assertions, see [Create a\nLocal Unit Test Class](/training/testing/local-tests#test-class).\n\nTo create an integration test for your content provider, you must perform these\nsteps:\n\n1. Create your test class as a subclass of `ProviderTestCase2`.\n2. Specify the [`AndroidJUnitRunner`](/reference/androidx/test/runner/AndroidJUnitRunner) class that [AndroidX Test](/training/testing) provides as your default test runner.\n3. Set the [`Context`](/reference/android/content/Context) object from the `ApplicationProvider` class. See the snippet below for an example.\n\n### Kotlin\n\n```kotlin\n@Throws(Exception::class)\noverride fun setUp() {\n super.setUp()\n context = ApplicationProvider.getApplicationContext\u003cContext\u003e()\n}\n```\n\n### Java\n\n```java\n@Override\nprotected void setUp() throws Exception {\n super.setUp();\n setContext(ApplicationProvider.getApplicationContext());\n}\n```\n\n### How ProviderTestCase2 works\n\nYou test a provider with a subclass of `ProviderTestCase2`. This base class\nextends [`AndroidTestCase`](/reference/android/test/AndroidTestCase), so it provides the JUnit testing framework as\nwell as Android-specific methods for testing application permissions. The most\nimportant feature of this class is its initialization, which creates the\nisolated test environment.\n\n#### Initialization\n\nThe initialization is done in the constructor for `ProviderTestCase2`,\nwhich subclasses call in their own constructors. The `ProviderTestCase2`\nconstructor creates an `IsolatedContext` object that allows file and\ndatabase operations but stubs out other interactions with the Android system.\nThe file and database operations themselves take place in a directory that is\nlocal to the device or emulator and has a special prefix.\n\nThe constructor then creates a `MockContentResolver` to use as the resolver\nfor the test.\n\nLastly, the constructor creates an instance of the provider under test. This is\na normal [`ContentProvider`](/reference/android/content/ContentProvider) object, but it takes all of its environment\ninformation from the `IsolatedContext`, so it is restricted to working in\nthe isolated test environment. All of the tests done in the test case class run\nagainst this isolated object.\n\nYou run integration tests for content providers the same way as instrumented\nunit tests.\n\nWhat to test\n------------\n\nHere are some specific guidelines for testing content providers.\n\n- **Test with resolver methods** : Even though you can instantiate a provider object in `ProviderTestCase2`, you should always test with a resolver object using the appropriate URI. Doing so ensures that you are testing the provider by performing the same interaction that a regular application would use.\n- **Test a public provider as a contract** : If you intend your provider to be public and available to other applications, you should test it as a contract. Some examples of how to do so are as follows:\n - Test with constants that your provider publicly exposes. For example, look for constants that refer to column names in one of the provider's data tables. These should always be constants publicly defined by the provider.\n - Test all the URIs that your provider offers. Your provider may offer several URIs, each one referring to a different aspect of the data.\n - Test invalid URIs. Your unit tests should deliberately call the provider with an invalid URI, and look for errors. A good provider design is to throw an `IllegalArgumentException` for invalid URIs.\n- **Test the standard provider interactions** : Most providers offer six access methods: `query()`, `insert()`, `delete()`, `update()`, `getType()`, and `onCreate()`. Your tests should verify that all of these methods work.\n- **Test business logic**: If the content provider implements business logic, you should test it. Business logic includes handling of invalid values, financial or arithmetic calculations, elimination, or combining of duplicates."]]