blob: 46ba7693e20097b55eabd827337430f88d6235c1 [file] [log] [blame]
Joe Malin90205432010-03-01 18:10:57 -08001page.title=Testing and Instrumentation
2@jd:body
Joe Malin5e173472010-05-07 21:30:44 -07003
Joe Malin90205432010-03-01 18:10:57 -08004<div id="qv-wrapper">
5 <div id="qv">
6 <h2>In this document</h2>
7 <ol>
8 <li>
9 <a href="#Overview">Overview</a>
10 </li>
11 <li>
12 <a href="#TestAPI">The Testing API</a>
13 <ol>
14 <li>
15 <a href="#Extensions">JUnit test case classes</a>
16 </li>
17 <li>
18 <a href="#Instrumentation">Instrumentation test case classes</a>
19 </li>
20 <li>
21 <a href="#Assert">Assert classes</a>
22 </li>
23 <li>
24 <a href="#MockObjects">Mock object classes</a>
25 </li>
26 <li>
27 <a href="#InstrumentationTestRunner">Instrumentation Test Runner</a>
28 </li>
29 </ol>
30 </li>
31 <li>
32 <a href="#TestEnviroment">Working in the Test Environment</a>
33 </li>
34 <li>
35 <a href="#TestAreas">What to Test</a>
36 </li>
37 <li>
38 <a href="#UITesting">Appendix: UI Testing Notes</a>
39 <ol>
40 <li>
41 <a href="#RunOnUIThread">Testing on the UI thread</a>
42 </li>
43 <li>
44 <a href="#NotouchMode">Turning off touch mode</a>
45 </li>
46 <li>
47 <a href="#UnlockDevice">Unlocking the Emulator or Device</a>
48 </li>
49 <li>
50 <a href="#UITestTroubleshooting">Troubleshooting UI tests</a>
51 </li>
52 </ol>
53 </li>
54 </ol>
55 <h2>Key Classes</h2>
56 <ol>
57 <li>{@link android.test.InstrumentationTestRunner}</li>
58 <li>{@link android.test.ActivityInstrumentationTestCase2}</li>
59 <li>{@link android.test.ActivityUnitTestCase}</li>
60 <li>{@link android.test.ApplicationTestCase}</li>
61 <li>{@link android.test.ProviderTestCase2}</li>
62 <li>{@link android.test.ServiceTestCase}</li>
63 </ol>
64 <h2>Related Tutorials</h2>
65 <ol>
66 <li>
67 <a href="{@docRoot}resources/tutorials/testing/helloandroid_test.html">Hello, Testing</a>
68 </li>
69 <li>
70 <a href="{@docRoot}resources/tutorials/testing/activity_test.html">Activity Testing</a>
71 </li>
72 </ol>
73 <h2>See Also</h2>
74 <ol>
75 <li>
Joe Malin5e173472010-05-07 21:30:44 -070076 <a href="{@docRoot}guide/developing/testing/testing_eclipse.html">Testing in Eclipse, with ADT</a>
Joe Malin90205432010-03-01 18:10:57 -080077 </li>
78 <li>
Joe Malin5e173472010-05-07 21:30:44 -070079 <a href="{@docRoot}guide/developing/testing/testing_otheride.html">Testing in Other IDEs</a>
Joe Malin90205432010-03-01 18:10:57 -080080 </li>
81 </ol>
82 </div>
83</div>
Joe Malin5e173472010-05-07 21:30:44 -070084
85<p>Android includes a powerful set of testing tools that extend the
86industry-standard JUnit test framework with features specific to the Android
87environment. Although you can test an Android application with JUnit, the
88Android tools allow you to write much more sophisticated tests for every aspect
89of your application, both at the unit and framework levels.</p>
90
91<p>Key features of the Android testing environment include:</p>
92
Joe Malin90205432010-03-01 18:10:57 -080093<ul>
Joe Malin5e173472010-05-07 21:30:44 -070094 <li>Android extensions to the JUnit framework that provide access to Android
95system objects.</li>
96 <li>An instrumentation framework that lets tests control and examine the
97application.</li>
Joe Malin90205432010-03-01 18:10:57 -080098 <li>Mock versions of commonly-used Android system objects.</li>
Joe Malin5e173472010-05-07 21:30:44 -070099 <li>Tools for running single tests or test suites, with or without
100instrumentation.</li>
101 <li>Support for managing tests and test projects in the ADT Plugin for Eclipse
102and at the command line.</li>
Joe Malin90205432010-03-01 18:10:57 -0800103</ul>
Joe Malin5e173472010-05-07 21:30:44 -0700104
105<p>This document is an overview of the Android testing environment and the way
106you use it. The document assumes you have a basic knowledge of Android
107application programming and JUnit testing methodology.</p>
108
Joe Malin90205432010-03-01 18:10:57 -0800109<h2 id="Overview">Overview</h2>
Joe Malin5e173472010-05-07 21:30:44 -0700110
111<p> At the heart of the Android testing environment is an instrumentation
112framework that your test application uses to precisely control the application
113under test. With instrumentation, you can set up mock system objects such as
114Contexts before the main application starts, control your application at various
115points of its lifecycle, send UI events to the application, and examine the
116application's state during its execution. The instrumentation framework
117accomplishes this by running both the main application and the test application
118in the same process. </p>
119
120<p>Your test application is linked to the application under test by means of an
121<a
122href="{@docRoot}guide/topics/manifest/instrumentation-element.html"><code>&lt;instrumentation&gt;</code></a>
123element in the test application's manifest file. The attributes of the element
124specify the package name of the application under test and also tell Android how
125to run the test application. Instrumentation is described in more detail in the
126section <a href="#InstrumentationTestRunner">Instrumentation Test
127Runner</a>.</p>
128
129<p>The following diagram summarizes the Android testing environment:</p>
130
Joe Malin90205432010-03-01 18:10:57 -0800131<img src="{@docRoot}images/testing/android_test_framework.png"/>
Joe Malin5e173472010-05-07 21:30:44 -0700132
133<p>In Android, test applications are themselves Android applications, so you
134write them in much the same way as the application you are testing. The SDK
135tools help you create a main application project and its test project at the same
136time. You can run Android tests within Eclipse with ADT or from the command
137line. Eclipse with ADT provides an extensive set of tools for creating tests,
138running them, and viewing their results. You can also use the <code>adb</code>
139tool to run tests, or use a built-in Ant target.</p>
140
141<p>To learn how to set up and run tests in Eclipse, please refer to <a
142href="{@docRoot}guide/developing/testing/testing_eclipse.html">Testing in
143Eclipse, with ADT</a>. If you're not working in Eclipse, refer to <a
144href="{@docRoot}guide/developing/testing/testing_otheride.html">Testing in Other
145IDEs</a>.</p>
146
147<p>If you want a step-by-step introduction to Android testing, try one of the
148testing tutorials:</p>
149
150<ul>
151 <li>The <a
152href="{@docRoot}resources/tutorials/testing/helloandroid_test.html">Hello,
153Testing</a> tutorial introduces basic testing concepts and procedures in the
154context of the Hello, World application.</li>
155 <li>The <a
156href="{@docRoot}resources/tutorials/testing/activity_test.html">Activity
157Testing</a> tutorial is an excellent follow-up to the Hello, Testing tutorial.
158It guides you through a more complex testing scenario that you develop against a
159more realistic application.</li>
160</ul>
161
Joe Malin90205432010-03-01 18:10:57 -0800162<h2 id="TestAPI">The Testing API</h2>
163<p>
164 For writing tests and test applications in the Java programming language, Android provides a
165 testing API that is based in part on the JUnit test framework. Adding to that, Android includes
166 a powerful instrumentation framework that lets your tests access the state and runtime objects
167 of the application under tests.
168</p>
169<p>The sections below describe the major components of the testing API available in Android.</p>
170<h3 id="Extensions">JUnit test case classes</h3>
171<p>
172 Some of the classes in the testing API extend the JUnit {@link junit.framework.TestCase TestCase} but do not use the instrumentation framework. These classes
173 contain methods for accessing system objects such as the Context of the application under test. With this Context, you can look at its resources, files, databases,
174 and so forth. The base class is {@link android.test.AndroidTestCase}, but you usually use a subclass associated with a particular component.
175<p>
176 The subclasses are:
177</p>
178 <ul>
179 <li>
180 {@link android.test.ApplicationTestCase} - A class for testing an entire application. It allows you to inject a mock Context into the application,
181 set up initial test parameters before the application starts, and examine the application after it finishes but before it is destroyed.
182 </li>
183 <li>
184 {@link android.test.ProviderTestCase2} - A class for isolated testing of a single {@link android.content.ContentProvider}. Since it is restricted to using a
185 {@link android.test.mock.MockContentResolver} for the provider, and it injects an {@link android.test.IsolatedContext}, your provider testing is isolated
186 from the rest of the OS.
187 </li>
188 <li>
189 {@link android.test.ServiceTestCase} - a class for isolated testing of a single {@link android.app.Service}. You can inject a mock Context or
190 mock Application (or both), or let Android provide you a full Context and a {@link android.test.mock.MockApplication}.
191 </li>
192 </ul>
193<h3 id="Instrumentation">Instrumentation test case classes</h3>
194<p>
195 The API for testing activities extends the JUnit {@link junit.framework.TestCase TestCase} class and also uses the instrumentation framework. With instrumentation,
196 Android can automate UI testing by sending events to the application under test, precisely control the start of an activity, and monitor the state of the
197 activity during its life cycle.
198</p>
199<p>
200 The base class is {@link android.test.InstrumentationTestCase}. All of its subclasses have the ability to send a keystroke or touch event to the UI of the application
201 under test. The subclasses can also inject a mock Intent.
202 The subclasses are:
203</p>
204 <ul>
205 <li>
206 {@link android.test.ActivityTestCase} - A base class for activity test classes.
207 </li>
208 <li>
209 {@link android.test.SingleLaunchActivityTestCase} - A convenience class for testing a single activity.
210 It invokes {@link junit.framework.TestCase#setUp() setUp()} and {@link junit.framework.TestCase#tearDown() tearDown()} only
211 once, instead of once per method call. Use it when all of your test methods run against the same activity.
212 </li>
213 <li>
214 {@link android.test.SyncBaseInstrumentation} - A class that tests synchronization of a content provider. It uses instrumentation to cancel and disable
215 existing synchronizations before starting the test synchronization.
216 </li>
217 <li>
218 {@link android.test.ActivityUnitTestCase} - This class does an isolated test of a single activity. With it, you can inject a mock context or application, or both.
219 It is intended for doing unit tests of an activity, and is the activity equivalent of the test classes described in <a href="#Extensions">JUnit test case classes</a>.
220 <p> Unlike the other instrumentation classes, this test class cannot inject a mock Intent.</p>
221 </li>
222 <li>
223 {@link android.test.ActivityInstrumentationTestCase2} - This class tests a single activity within the normal system environment.
224 You cannot inject a mock Context, but you can inject mock Intents. Also, you can run a test method on the UI thread (the main thread of the application under test),
225 which allows you to send key and touch events to the application UI.
226 </li>
227 </ul>
228<h3 id="Assert">Assert classes</h3>
229<p>
230 Android also extends the JUnit {@link junit.framework.Assert} class that is the basis of <code>assert()</code> calls in tests.
231 There are two extensions to this class, {@link android.test.MoreAsserts} and {@link android.test.ViewAsserts}:
232</p>
233<ul>
234 <li>
235 The <code>MoreAsserts</code> class contains more powerful assertions such as {@link android.test.MoreAsserts#assertContainsRegex} that does regular expression matching.
236 </li>
237 <li>
238 The {@link android.test.ViewAsserts} class contains useful assertions about Android Views, such as {@link android.test.ViewAsserts#assertHasScreenCoordinates} that tests if a View has a particular X and Y
239 position on the visible screen. These asserts simplify testing of geometry and alignment in the UI.
240 </li>
241</ul>
242<h3 id="MockObjects">Mock object classes</h3>
243 <p>
244 Android has convenience classes for creating mock system objects such as applications, contexts, content resolvers, and resources. Android also provides
245 methods in some test classes for creating mock Intents. Use these mocks to facilitate dependency injection, since they are easier to use than creating their
246 real counterparts. These convenience classes are found in {@link android.test} and {@link android.test.mock}. They are:
247 </p>
248 <ul>
249 <li>
250 {@link android.test.IsolatedContext} - Mocks a Context so that the application using it runs in isolation.
251 At the same time, it has enough stub code to satisfy OS code that tries to communicate with contexts. This class is useful in unit testing.
252 </li>
253 <li>
254 {@link android.test.RenamingDelegatingContext} - Delegates most context functions to an existing, normal context while changing the default file and database
255 names in the context. Use this to test file and database operations with a normal system context, using test names.
256 </li>
257 <li>
258 {@link android.test.mock.MockApplication}, {@link android.test.mock.MockContentResolver}, {@link android.test.mock.MockContext},
259 {@link android.test.mock.MockDialogInterface}, {@link android.test.mock.MockPackageManager},
260 {@link android.test.mock.MockResources} - Classes that create mock Android system objects for use in testing. They expose only those methods that are
261 useful in managing the object. The default implementations of these methods simply throw an Exception. You are expected to extend the classes and
262 override any methods that are called by the application under test.
263 </li>
264 </ul>
265<h3 id="InstrumentationTestRunner">Instrumentation Test Runner</h3>
266<p>
267 Android provides a custom class for running tests with instrumentation called called
268 {@link android.test.InstrumentationTestRunner}. This class
269 controls of the application under test, runs the test application and the main application in the same process, and routes
270 test output to the appropriate place. Using instrumentation is key to the ability of <code>InstrumentationTestRunner</code> to control the entire test
271 environment at runtime. Notice that you use this test runner even if your test class does not itself use instrumentation.
272</p>
273<p>
274 When you run a test application, you first run a system utility called Activity Manager. Activity Manager uses the instrumentation framework to start and control the test runner, which in turn uses instrumentation to shut down any running instances
275 of the main application, starts the test application, and then starts the main application in the same process. This allows various aspects of the test application to work directly with the main application.
276</p>
277<p>
278 If you are developing in Eclipse, the ADT plugin assists you in the setup of <code>InstrumentationTestRunner</code> or other test runners.
279 The plugin UI prompts you to specify the test runner class to use, as well as the package name of the application under test.
280 The plugin then adds an <code>&lt;instrumentation&gt;</code> element with appropriate attributes to the manifest file of the test application.
281 Eclipse with ADT automatically starts a test application under the control of Activity Manager using instrumentation,
282 and redirects the test output to the Eclipse window's JUnit view.
283</p>
284<p>
285 If you prefer working from the command line, you can use Ant and the <code>android</code>
286 tool to help you set up your test projects. To run tests with instrumentation, you can access the
287 Activity Manager through the <a href="{@docRoot}guide/developing/tools/adb.html">Android Debug
288 Bridge</a> (<code>adb</code>) tool and the output is directed to <code>STDOUT</code>.
289</p>
290<h2 id="TestEnviroment">Working in the Test Environment</h2>
291<p>
292 The tests for an Android application are contained in a test application, which itself is an Android application. A test application resides in a separate Android project that has the
293 same files and directories as a regular Android application. The test project is linked to the project of the application it tests
294 (known as the application under test) by its manifest file.
295</p>
296<p>
297 Each test application contains one or more test case classes based on an Android class for a
298 particular type of component. The test case class contains methods that define tests on some part of the application under test. When you run the test application, Android
299 starts it, loads the application under test into the same process, and then invokes each method in the test case class.
300</p>
301<p>
302 The tools and procedures you use with testing depend on the development environment you are using. If you use Eclipse, then the ADT plug in for Eclipse provides tools that
Joe Malin5e173472010-05-07 21:30:44 -0700303 allow you to develop and run tests entirely within Eclipse. This is documented in the topic <a href="{@docRoot}guide/developing/testing/testing_eclipse.html">Testing in Eclipse, with ADT</a>.
304 If you use another development environment, then you use Android's command-line tools, as documented in the topic <a href="{@docRoot}guide/developing/testing/testing_otheride.html">Testing in Other IDEs</a>.
Joe Malin90205432010-03-01 18:10:57 -0800305</p>
306<h3 id="TestProjects">Working with test projects</h3>
307<p>
308 To start testing an Android application, you create a test project for it using Android tools. The tools create the project directory and the files and subdirectories needed.
309 The tools also create a manifest file that links the application in the test project to the application under test. The procedure for creating a test project in Eclipse with
Joe Malin5e173472010-05-07 21:30:44 -0700310 ADT is documented in <a href="{@docRoot}guide/developing/testing/testing_eclipse.html">Testing in Eclipse, with ADT</a>. The procedure for creating a test project for use with development
311 tools other than Eclipse is documented in <a href="{@docRoot}guide/developing/testing/testing_otheride.html">Testing in Other IDEs</a>.
Joe Malin90205432010-03-01 18:10:57 -0800312</p>
313<h3 id="TestClasses">Working with test case classes</h3>
314<p>
315 A test application contains one or more test case classes that extend an Android test case class. You choose a test case class based on the type of Android component you are testing and the
316 tests you are doing. A test application can test different components, but each test case class is designed to test a single type of component.
317 The Android test case classes are described in the section <a href="#TestAPI">The Testing API</a>.
318</p>
319<p>
320 Some Android components have more than one associated test case class. In this case, you choose among the available classes based on the type of tests you want to do. For activities,
321 for example, you have the choice of either {@link android.test.ActivityInstrumentationTestCase2} or {@link android.test.ActivityUnitTestCase}.
322<p>
323 <code>ActivityInstrumentationTestCase2</code> is designed to do functional testing, so it tests activities in a normal system infrastructure. You can inject mocked Intents, but not
324 mocked Contexts. In general, you can't mock dependencies for the activity under test.
325</p>
326<p>
327 In comparison, <code>ActivityUnitTestCase</code> is designed for unit testing, so it tests activities in an isolated system infrastructure. You can inject mocked or wrappered dependencies for
328 the activity under test, particularly mocked Contexts. On the other hand, when you use this test case class the activity under test runs in isolation and can't interact with other activities.
329</p>
330<p>
331 As a rule of thumb, if you wanted to test an activity's interaction with the rest of Android, you would use <code>ActivityInstrumentationTestCase2</code>. If you wanted to do regression testing
332 on an activity, you would use <code>ActivityUnitTestCase</code>.
333</p>
334<h3 id="Tests">Working with test methods</h3>
335<p>
336 Each test case class provides methods that you use to set up the test environment and control the application under test. For example, all test case classes provide the JUnit {@link junit.framework.TestCase#setUp() setUp()}
337 method that you can override to set up fixtures. In addition, you add methods to the class to define individual tests. Each method you add is run once each time you run the test application. If you override the <code>setUp()</code>
338 method, it runs before each of your methods. Similarly, the JUnit {@link junit.framework.TestCase#tearDown() tearDown()} method is run once after each of your methods.
339</p>
340<p>
341 The test case classes give you substantial control over starting and stopping components. For this reason, you have to specifically tell Android to start a component before you run tests against it. For example, you use the
342 {@link android.test.ActivityInstrumentationTestCase2#getActivity()} method to start the activity under test. You can call this method once during the entire test case, or once for each test method. You can even destroy the
343 activity under test by calling its {@link android.app.Activity#finish()} method and then restart it with <code>getActivity()</code> within a single test method.
344</p>
345<h3 id="RunTests">Running tests and seeing the results</h3>
346<p>
347 To run your tests, you build your test project and then run the test application using the system utility Activity Manager with instrumentation. You provide to Activity Manager the name of the test runner (usually
348 {@link android.test.InstrumentationTestRunner}) you specified for your application; the name includes both your test application's package name and the test runner class name. Activity Manager loads and starts your
349 test application, kills any instances of the application under test, loads an instance of the application under test into the same process as the test application, and then passes control to the first test case
350 class in your test application. The test runner then takes control of the tests, running each of your test methods against the application under test until all the methods in all the classes have been run.
351</p>
352<p>
353 If you run a test within Eclipse with ADT, the output appears in a new JUnit view pane. If you run a test from the command line, the output goes to STDOUT.
354</p>
355<h2 id="TestAreas">What to Test</h2>
356<p>
357 In addition to the functional areas you would normally test, here are some areas
358 of Android application testing that you should consider:
359</p>
360 <ul>
361 <li>
362 Activity lifecycle events: You should test that your activities handle lifecycle events correctly. For example
363 an activity should respond to pause or destroy events by saving its state. Remember that even a change in screen orientation
364 causes the current activity to be destroyed, so you should test that accidental device movements don't accidentally lose the
365 application state.
366 </li>
367 <li>
368 Database operations: You should ensure that database operations correctly handle changes to the application's state.
369 To do this, use mock objects from the package {@link android.test.mock android.test.mock}.
370 </li>
371 <li>
372 Screen sizes and resolutions: Before you publish your application, make sure to test it on all of the
373 screen sizes and densities on which you want it to run. You can test the application on multiple sizes and densities using
374 AVDs, or you can test your application directly on the devices that you are targeting. For more information, see
375 the topic <a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a>.
376 </li>
377 </ul>
378<p>
379 When possible, you should run these tests on an actual device. If this is not possible, you can
380 use the <a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a> with
381 <a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a> configured for
382 the hardware, screens, and versions you want to test.
383</p>
384<h2 id="UITesting">Appendix: UI Testing Notes</h2>
385<p>
386 The following sections have tips for testing the UI of your Android application, specifically
387 to help you handle actions that run in the UI thread, touch screen and keyboard events, and home
388 screen unlock during testing.
389</p>
390<h3 id="RunOnUIThread">Testing on the UI thread</h3>
391<p>
392 An application's activities run on the application's <strong>UI thread</strong>. Once the
393 UI is instantiated, for example in the activity's <code>onCreate()</code> method, then all
394 interactions with the UI must run in the UI thread. When you run the application normally, it
395 has access to the thread and does not have to do anything special.
396</p>
397<p>
398 This changes when you run tests against the application. With instrumentation-based classes,
399 you can invoke methods against the UI of the application under test. The other test classes don't allow this.
400 To run an entire test method on the UI thread, you can annotate the thread with <code>@UIThreadTest</code>.
401 Notice that this will run <em>all</em> of the method statements on the UI thread. Methods that do not interact with the UI
402 are not allowed; for example, you can't invoke <code>Instrumentation.waitForIdleSync()</code>.
403</p>
404<p>
405 To run a subset of a test method on the UI thread, create an anonymous class of type
406 <code>Runnable</code>, put the statements you want in the <code>run()</code> method, and instantiate a new
407 instance of the class as a parameter to the method <code><em>appActivity</em>.runOnUiThread()</code>, where
408 <code><em>appActivity</em></code> is the instance of the app you are testing.
409</p>
410<p>
411 For example, this code instantiates an activity to test, requests focus (a UI action) for the Spinner displayed
412 by the activity, and then sends a key to it. Notice that the calls to <code>waitForIdleSync</code> and <code>sendKeys</code>
413 aren't allowed to run on the UI thread:</p>
414<pre>
415 private MyActivity mActivity; // MyActivity is the class name of the app under test
416 private Spinner mSpinner;
417
418 ...
419
420 protected void setUp() throws Exception {
421 super.setUp();
422 mInstrumentation = getInstrumentation();
423
424 mActivity = getActivity(); // get a references to the app under test
425
426 /*
427 * Get a reference to the main widget of the app under test, a Spinner
428 */
429 mSpinner = (Spinner) mActivity.findViewById(com.android.demo.myactivity.R.id.Spinner01);
430
431 ...
432
433 public void aTest() {
434 /*
435 * request focus for the Spinner, so that the test can send key events to it
436 * This request must be run on the UI thread. To do this, use the runOnUiThread method
437 * and pass it a Runnable that contains a call to requestFocus on the Spinner.
438 */
439 mActivity.runOnUiThread(new Runnable() {
440 public void run() {
441 mSpinner.requestFocus();
442 }
443 });
444
445 mInstrumentation.waitForIdleSync();
446
447 this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
448</pre>
449
450<h3 id="NotouchMode">Turning off touch mode</h3>
451<p>
452 To control the emulator or a device with key events you send from your tests, you must turn off
453 touch mode. If you do not do this, the key events are ignored.
454</p>
455<p>
456 To turn off touch mode, you invoke <code>ActivityInstrumentationTestCase2.setActivityTouchMode(false)</code>
457 <em>before</em> you call <code>getActivity()</code> to start the activity. You must invoke the method in a test method
458 that is <em>not</em> running on the UI thread. For this reason, you can't invoke the touch mode method
459 from a test method that is annotated with <code>@UIThread</code>. Instead, invoke the touch mode method from <code>setUp()</code>.
460</p>
461<h3 id="UnlockDevice">Unlocking the emulator or device</h3>
462<p>
463 You may find that UI tests don't work if the emulator's or device's home screen is disabled with the keyguard pattern.
464 This is because the application under test can't receive key events sent by <code>sendKeys()</code>. The best
465 way to avoid this is to start your emulator or device first and then disable the keyguard for the home screen.
466</p>
467<p>
468 You can also explicitly disable the keyguard. To do this,
469 you need to add a permission in the manifest file (<code>AndroidManifest.xml</code>) and
470 then disable the keyguard in your application under test. Note, though, that you either have to remove this before
471 you publish your application, or you have to disable it programmatically in the published app.
472</p>
473<p>
474 To add the the permission, add the element <code>&lt;uses-permission android:name="android.permission.DISABLE_KEYGUARD"/&gt;</code>
475 as a child of the <code>&lt;manifest&gt;</code> element. To disable the KeyGuard, add the following code
476 to the <code>onCreate()</code> method of activities you intend to test:
477</p>
478<pre>
479 mKeyGuardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
480 mLock = mKeyGuardManager.newKeyguardLock("<em>activity_classname</em>");
481 mLock.disableKeyguard();
482</pre>
483<p>where <code><em>activity_classname</em></code> is the class name of the activity.</p>
484<h3 id="UITestTroubleshooting">Troubleshooting UI tests</h3>
485<p>
486 This section lists some of the common test failures you may encounter in UI testing, and their causes:
487</p>
488<dl>
489 <dt><code>WrongThreadException</code></dt>
490 <dd>
491 <p><strong>Problem:</strong></p>
492 For a failed test, the Failure Trace contains the following error message:
493 <code>
494 android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
495 </code>
496 <p><strong>Probable Cause:</strong></p>
497 This error is common if you tried to send UI events to the UI thread from outside the UI thread. This commonly happens if you send UI events
498 from the test application, but you don't use the <code>@UIThread</code> annotation or the <code>runOnUiThread()</code> method. The test method tried to interact with the UI outside the UI thread.
499 <p><strong>Suggested Resolution:</strong></p>
500 Run the interaction on the UI thread. Use a test class that provides instrumentation. See the previous section <a href="#RunOnUIThread">Testing on the UI Thread</a>
501 for more details.
502 </dd>
503 <dt><code>java.lang.RuntimeException</code></dt>
504 <dd>
505 <p><strong>Problem:</strong></p>
506 For a failed test, the Failure Trace contains the following error message:
507 <code>
508 java.lang.RuntimeException: This method can not be called from the main application thread
509 </code>
510 <p><strong>Probable Cause:</strong></p>
511 This error is common if your test method is annotated with <code>@UiThreadTest</code> but then tries to
512 do something outside the UI thread or tries to invoke <code>runOnUiThread()</code>.
513 <p><strong>Suggested Resolution:</strong></p>
514 Remove the <code>@UiThreadTest</code> annotation, remove the <code>runOnUiThread()</code> call, or re-factor your tests.
515 </dd>
516</dl>
517