1page.title=Testing Your Content Provider
2page.tags=testing, content provider
3trainingnavtop=true
4
5@jd:body
6
7<!-- This is the training bar -->
8<div id="tb-wrapper">
9<div id="tb">
10  <h2>Dependencies and Prerequisites</h2>
11
12  <ul>
13    <li>Android 2.2 (API level 8) or higher</li>
14    <li><a href="{@docRoot}tools/testing-support-library/index.html">
15      Android Testing Support Library</a></li>
16    <li><a href="{@docRoot}tools/studio/index.html">Android Studio 1.4.1 or higher</a>.</li>
17  </ul>
18
19  <h2>This lesson teaches you to</h2>
20
21  <ol>
22    <li><a href="#build">Create Integration Tests for Content Providers</a></li>
23    <li><a href="#WhatToTest">What to Test</a></li>
24  </ol>
25
26  <h2>You should also read</h2>
27  <ul>
28      <li><a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
29      </li>
30  </ul>
31</div>
32</div>
33
34<p>
35    If you are implementing a <a href="{@docRoot}guide/topics/providers/content-providers.html">
36    content provider</a> to store and retrieve data or to make data
37    accessible to other apps, you should test your provider to ensure that it doesn't behave in an
38    unexpected way. This lesson describes how to test public content providers, and is also
39    applicable to providers that you keep private to your own app.
40</p>
41<h2 id="build">Create Integration Tests for Content Providers</h2>
42<p>
43In Android, apps view content providers as data APIs that provide
44tables of data, with their internals hidden from view. A content provider may have many
45public constants, but it usually has few if any public methods and no public variables.
46For this reason, you should write your tests based only on the provider's public members.
47A content provider that is designed like this is offering a contract between itself and its users.
48</p>
49<p>
50Content providers let you access actual user data, so it's important to ensure
51that you test the content provider in an isolated testing environment. This approach allows you to
52only run against data dependencies set explicitly in the test case. It also means that your tests
53do not modify actual user data. For example, you should avoid writing a test that fails because
54there was data left over from a previous test. Similarly, your test should avoid adding or deleting
55actual contact information in a provider.
56</p>
57
58<p>
59To test your content provider in isolation, use the {@link android.test.ProviderTestCase2} class.
60This class allows you to use Android mock object classes such as {@link android.test.IsolatedContext}
61and {@link android.test.mock.MockContentResolver} to access file and database information without
62affecting the actual user data.
63</p>
64
65<p>Your integration test should be written as a JUnit 4 test class. To learn more about creating
66JUnit 4 test classes and using JUnit 4 assertions, see
67<a href="{@docRoot}training/testing/unit-testing/local-unit-tests.html#build">
68Create a Local Unit Test Class</a>.</p>
69
70<p>To create an integration test for your content provider, you must perform these steps:</p>
71<ul>
72    <li>Create your test class as a subclass of {@link android.test.ProviderTestCase2}.</li>
73    <li>Add the
74{@code &#64;RunWith(AndroidJUnit4.class)} annotation at the beginning of your test class
75definition.</li>
76    <li>Specify the
77<a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">
78{@code AndroidJUnitRunner}</a> class that the
79<a href="{@docRoot}tools/testing-support-library/index.html">Android Testing Support Library</a>
80provides as your default test runner. This step is described in more detail in
81<a href="{@docRoot}training/testing/start/index.html#run-instrumented-tests">
82Getting Started with Testing</a>.</li>
83    <li>Set the {@link android.content.Context} object from the
84<a href="{@docRoot}reference/android/support/test/InstrumentationRegistry.html">
85{@code InstrumentationRegistry}</a> class. See the snippet below for an example.
86    <pre>
87&#64;Override
88protected void setUp() throws Exception {
89    setContext(InstrumentationRegistry.getTargetContext());
90    super.setUp();
91}</pre>
92    </li>
93</ul>
94
95<h3 id="ProviderTestCase2">How ProviderTestCase2 works</h3>
96<p>
97    You test a provider with a subclass of {@link android.test.ProviderTestCase2}. This base class
98    extends {@link android.test.AndroidTestCase}, so it provides the JUnit testing framework as well
99    as Android-specific methods for testing application permissions. The most important
100    feature of this class is its initialization, which creates the isolated test environment.
101</p>
102<p>
103    The initialization is done in the constructor for {@link android.test.ProviderTestCase2}, which
104    subclasses call in their own constructors. The {@link android.test.ProviderTestCase2}
105    constructor creates an {@link android.test.IsolatedContext} object that allows file and
106    database operations but stubs out other interactions with the Android system.
107    The file and database operations themselves take place in a directory that is local to the
108    device or emulator and has a special prefix.
109</p>
110<p>
111    The constructor then creates a {@link android.test.mock.MockContentResolver} to use as the
112    resolver for the test.
113</p>
114<p>
115    Lastly, the constructor creates an instance of the provider under test. This is a normal
116    {@link android.content.ContentProvider} object, but it takes all of its environment information
117    from the {@link android.test.IsolatedContext}, so it is restricted to
118    working in the isolated test environment. All of the tests done in the test case class run
119    against this isolated object.
120</p>
121
122<p>
123You run integration tests for content providers the same way as instrumented unit tests. To run the
124integration test for your content provider, follow the steps described in <a
125href="{@docRoot}training/testing/unit-testing/instrumented-unit-tests.html#run">
126Run Instrumented Unit Tests</a>.
127</p>
128
129<h2 id="WhatToTest">What to Test</h2>
130<p>
131Here are some specific guidelines for testing content providers.
132</p>
133<ul>
134    <li>
135        Test with resolver methods: Even though you can instantiate a provider object in
136        {@link android.test.ProviderTestCase2}, you should always test with a resolver object
137        using the appropriate URI. Doing so ensures that you are testing the provider by performing
138        the same interaction that a regular application would use.
139    </li>
140    <li>
141        Test a public provider as a contract: If you intend your provider to be public and
142        available to other applications, you should test it as a contract. Some examples of how to
143        do so are as follows:
144        <ul>
145            <li>
146                Test with constants that your provider publicly exposes. For
147                example, look for constants that refer to column names in one of the provider's
148                data tables. These should always be constants publicly defined by the provider.
149            </li>
150            <li>
151                Test all the URIs that your provider offers. Your provider may offer several URIs,
152                each one referring to a different aspect of the data.
153            </li>
154            <li>
155                Test invalid URIs: Your unit tests should deliberately call the provider with an
156                invalid URI, and look for errors. A good provider design is to throw an
157                {@code IllegalArgumentException} for invalid URIs.
158
159            </li>
160        </ul>
161    </li>
162    <li>
163        Test the standard provider interactions: Most providers offer six access methods:
164        {@code query()}, {@code insert()}, {@code delete()}, {@code update()},
165        {@code getType()}, and {@code onCreate()}. Your tests should verify that all
166        of these methods work. These methods are described in more detail in the topic
167        <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>.
168    </li>
169    <li>
170        Test business logic: If the content provider implements business logic, you should test it.
171        Business logic includes handling of invalid values, financial or arithmetic calculations,
172        elimination or combining of duplicates.
173    </li>
174</ul>