1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.test;
18 
19 import android.app.Application;
20 import android.app.Instrumentation;
21 import android.content.Context;
22 
23 /**
24  * This test case provides a framework in which you can test Application classes in
25  * a controlled environment.  It provides basic support for the lifecycle of a
26  * Application, and hooks by which you can inject various dependencies and control
27  * the environment in which your Application is tested.
28  *
29  * <p><b>Lifecycle Support.</b>
30  * Every Application is designed to be accessed within a specific sequence of
31  * method calls (see {@link android.app.Application} for more details).
32  * In order to support the lifecycle of a Application, this test case will make the
33  * following calls at the following times.
34  *
35  * <ul><li>The test case will not call onCreate() until your test calls
36  * {@link #createApplication()}.  This gives you a chance
37  * to set up or adjust any additional framework or test logic before
38  * onCreate().</li>
39  * <li>After your test completes, the test case {@link #tearDown} method is
40  * automatically called, and it will stop & destroy your application by calling its
41  * onDestroy() method.</li>
42  * </ul>
43  *
44  * <p><b>Dependency Injection.</b>
45  * Every Application has one inherent dependency, the {@link android.content.Context Context} in
46  * which it runs.
47  * This framework allows you to inject a modified, mock, or isolated replacement for this
48  * dependencies, and thus perform a true unit test.
49  *
50  * <p>If simply run your tests as-is, your Application will be injected with a fully-functional
51  * Context.
52  * You can create and inject alternative types of Contexts by calling
53  * {@link AndroidTestCase#setContext(Context) setContext()}.  You must do this <i>before</i> calling
54  * {@link #createApplication()}.  The test framework provides a
55  * number of alternatives for Context, including {@link android.test.mock.MockContext MockContext},
56  * {@link android.test.RenamingDelegatingContext RenamingDelegatingContext}, and
57  * {@link android.content.ContextWrapper ContextWrapper}.
58  */
59 public abstract class ApplicationTestCase<T extends Application> extends AndroidTestCase {
60 
61     Class<T> mApplicationClass;
62 
63     private Context mSystemContext;
64 
ApplicationTestCase(Class<T> applicationClass)65     public ApplicationTestCase(Class<T> applicationClass) {
66         mApplicationClass = applicationClass;
67     }
68 
69     private T mApplication;
70     private boolean mAttached = false;
71     private boolean mCreated = false;
72 
73     /**
74      * @return Returns the actual Application under test.
75      */
getApplication()76     public T getApplication() {
77         return mApplication;
78     }
79 
80     /**
81      * This will do the work to instantiate the Application under test.  After this, your test
82      * code must also start and stop the Application.
83      */
84     @Override
setUp()85     protected void setUp() throws Exception {
86         super.setUp();
87 
88         // get the real context, before the individual tests have a chance to muck with it
89         mSystemContext = getContext();
90     }
91 
92     /**
93      * Load and attach the application under test.
94      */
setupApplication()95     private void setupApplication() {
96         mApplication = null;
97         try {
98             mApplication = (T) Instrumentation.newApplication(mApplicationClass, getContext());
99         } catch (Exception e) {
100             assertNotNull(mApplication);
101         }
102         mAttached = true;
103     }
104 
105     /**
106      * Start the Application under test, in the same way as if it was started by the system.
107      * If you use this method to start the Application, it will automatically
108      * be stopped by {@link #tearDown}.  If you wish to inject a specialized Context for your
109      * test, by calling {@link AndroidTestCase#setContext(Context) setContext()},
110      * you must do so  before calling this method.
111      */
createApplication()112     final protected void createApplication() {
113         assertFalse(mCreated);
114 
115         if (!mAttached) {
116             setupApplication();
117         }
118         assertNotNull(mApplication);
119 
120         mApplication.onCreate();
121         mCreated = true;
122     }
123 
124     /**
125      * This will make the necessary calls to terminate the Application under test (it will
126      * call onTerminate().  Ordinarily this will be called automatically (by {@link #tearDown}, but
127      * you can call it directly from your test in order to check for proper shutdown behaviors.
128      */
terminateApplication()129     final protected void terminateApplication() {
130         if (mCreated) {
131             mApplication.onTerminate();
132         }
133     }
134 
135     /**
136      * Shuts down the Application under test.  Also makes sure all resources are cleaned up and
137      * garbage collected before moving on to the next
138      * test.  Subclasses that override this method should make sure they call super.tearDown()
139      * at the end of the overriding method.
140      *
141      * @throws Exception
142      */
143     @Override
tearDown()144     protected void tearDown() throws Exception {
145         terminateApplication();
146         mApplication = null;
147 
148         // Scrub out members - protects against memory leaks in the case where someone
149         // creates a non-static inner class (thus referencing the test case) and gives it to
150         // someone else to hold onto
151         scrubClass(ApplicationTestCase.class);
152 
153         super.tearDown();
154     }
155 
156     /**
157      * Return a real (not mocked or instrumented) system Context that can be used when generating
158      * Mock or other Context objects for your Application under test.
159      *
160      * @return Returns a reference to a normal Context.
161      */
getSystemContext()162     public Context getSystemContext() {
163         return mSystemContext;
164     }
165 
166     /**
167      * This test simply confirms that the Application class can be instantiated properly.
168      *
169      * @throws Exception
170      */
testApplicationTestCaseSetUpProperly()171     final public void testApplicationTestCaseSetUpProperly() throws Exception {
172         setupApplication();
173         assertNotNull("Application class could not be instantiated successfully", mApplication);
174     }
175 }
176