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
17package android.test;
18
19import android.app.Application;
20import android.app.Service;
21import android.content.Context;
22import android.content.Intent;
23import android.os.IBinder;
24import android.test.mock.MockApplication;
25
26import android.test.mock.MockService;
27import java.util.Random;
28
29/**
30 * This test case provides a framework in which you can test Service classes in
31 * a controlled environment.  It provides basic support for the lifecycle of a
32 * Service, and hooks with which you can inject various dependencies and control
33 * the environment in which your Service is tested.
34 *
35 * <div class="special reference">
36 * <h3>Developer Guides</h3>
37 * <p>For more information about application testing, read the
38 * <a href="{@docRoot}guide/topics/testing/index.html">Testing</a> developer guide.</p>
39 * </div>
40 *
41 * <p><b>Lifecycle Support.</b>
42 * A Service is accessed with a specific sequence of
43 * calls, as described in the
44 * <a href="http://developer.android.com/guide/topics/fundamentals/services.html">Services</a>
45 * document. In order to support the lifecycle of a Service,
46 * <code>ServiceTestCase</code> enforces this protocol:
47 *
48 * <ul>
49 *      <li>
50 *          The {@link #setUp()} method is called before each test method. The base implementation
51 *          gets the system context. If you override <code>setUp()</code>, you must call
52 *          <code>super.setUp()</code> as the first statement in your override.
53 *      </li>
54 *      <li>
55 *          The test case waits to call {@link android.app.Service#onCreate()} until one of your
56 *          test methods calls {@link #startService} or {@link #bindService}.  This gives you an
57 *          opportunity to set up or adjust any additional framework or test logic before you test
58 *          the running service.
59 *      </li>
60 *      <li>
61 *          When one of your test methods calls {@link #startService ServiceTestCase.startService()}
62 *          or {@link #bindService  ServiceTestCase.bindService()}, the test case calls
63 *          {@link android.app.Service#onCreate() Service.onCreate()} and then calls either
64 *          {@link android.app.Service#startService(Intent) Service.startService(Intent)} or
65 *          {@link android.app.Service#bindService(Intent, ServiceConnection, int)
66 *          Service.bindService(Intent, ServiceConnection, int)}, as appropriate. It also stores
67 *          values needed to track and support the lifecycle.
68 *      </li>
69 *      <li>
70 *          After each test method finishes, the test case calls the {@link #tearDown} method. This
71 *          method stops and destroys the service with the appropriate calls, depending on how the
72 *          service was started. If you override <code>tearDown()</code>, your must call the
73 *          <code>super.tearDown()</code> as the last statement in your override.
74 *      </li>
75 * </ul>
76 *
77 * <p>
78 *      <strong>Dependency Injection.</strong>
79 *      A service has two inherent dependencies, its {@link android.content.Context Context} and its
80 *      associated {@link android.app.Application Application}. The ServiceTestCase framework
81 *      allows you to inject modified, mock, or isolated replacements for these dependencies, and
82 *      thus perform unit tests with controlled dependencies in an isolated environment.
83 * </p>
84 * <p>
85 *      By default, the test case is injected with a full system context and a generic
86 *      {@link android.test.mock.MockApplication MockApplication} object. You can inject
87 *      alternatives to either of these by invoking
88 *      {@link AndroidTestCase#setContext(Context) setContext()} or
89 *      {@link #setApplication setApplication()}.  You must do this <em>before</em> calling
90 *      startService() or bindService().  The test framework provides a
91 *      number of alternatives for Context, including
92 *      {@link android.test.mock.MockContext MockContext},
93 *      {@link android.test.RenamingDelegatingContext RenamingDelegatingContext},
94 *      {@link android.content.ContextWrapper ContextWrapper}, and
95 *      {@link android.test.IsolatedContext}.
96 *
97 * @deprecated Use
98 * <a href="{@docRoot}reference/android/support/test/rule/ServiceTestRule.html">
99 * ServiceTestRule</a> instead. New tests should be written using the
100 * <a href="{@docRoot}tools/testing-support-library/index.html">Android Testing Support Library</a>.
101 */
102@Deprecated
103public abstract class ServiceTestCase<T extends Service> extends AndroidTestCase {
104
105    Class<T> mServiceClass;
106
107    private Context mSystemContext;
108    private Application mApplication;
109
110    /**
111     * Constructor
112     * @param serviceClass The type of the service under test.
113     */
114    public ServiceTestCase(Class<T> serviceClass) {
115        mServiceClass = serviceClass;
116    }
117
118    private T mService;
119    private boolean mServiceAttached = false;
120    private boolean mServiceCreated = false;
121    private boolean mServiceStarted = false;
122    private boolean mServiceBound = false;
123    private Intent mServiceIntent = null;
124    private int mServiceId;
125
126    /**
127     * @return An instance of the service under test. This instance is created automatically when
128     * a test calls {@link #startService} or {@link #bindService}.
129     */
130    public T getService() {
131        return mService;
132    }
133
134    /**
135     * Gets the current system context and stores it.
136     *
137     * Extend this method to do your own test initialization. If you do so, you
138     * must call <code>super.setUp()</code> as the first statement in your override. The method is
139     * called before each test method is executed.
140     */
141    @Override
142    protected void setUp() throws Exception {
143        super.setUp();
144
145        // get the real context, before the individual tests have a chance to muck with it
146        mSystemContext = getContext();
147
148    }
149
150    /**
151     * Creates the service under test and attaches all injected dependencies
152     * (Context, Application) to it.  This is called automatically by {@link #startService} or
153     * by {@link #bindService}.
154     * If you need to call {@link AndroidTestCase#setContext(Context) setContext()} or
155     * {@link #setApplication setApplication()}, do so before calling this method.
156     */
157    protected void setupService() {
158        mService = null;
159        try {
160            mService = mServiceClass.newInstance();
161        } catch (Exception e) {
162            assertNotNull(mService);
163        }
164        if (getApplication() == null) {
165            setApplication(new MockApplication());
166        }
167        MockService.attachForTesting(
168                mService, getContext(), mServiceClass.getName(), getApplication());
169
170        assertNotNull(mService);
171
172        mServiceId = new Random().nextInt();
173        mServiceAttached = true;
174    }
175
176    /**
177     * Starts the service under test, in the same way as if it were started by
178     * {@link android.content.Context#startService(Intent) Context.startService(Intent)} with
179     * an {@link android.content.Intent} that identifies a service.
180     * If you use this method to start the service, it is automatically stopped by
181     * {@link #tearDown}.
182     *
183     * @param intent An Intent that identifies a service, of the same form as the Intent passed to
184     * {@link android.content.Context#startService(Intent) Context.startService(Intent)}.
185     */
186    protected void startService(Intent intent) {
187        if (!mServiceAttached) {
188            setupService();
189        }
190        assertNotNull(mService);
191
192        if (!mServiceCreated) {
193            mService.onCreate();
194            mServiceCreated = true;
195        }
196        mService.onStartCommand(intent, 0, mServiceId);
197
198        mServiceStarted = true;
199    }
200
201    /**
202     * <p>
203     *      Starts the service under test, in the same way as if it were started by
204     *      {@link android.content.Context#bindService(Intent, ServiceConnection, int)
205     *      Context.bindService(Intent, ServiceConnection, flags)} with an
206     *      {@link android.content.Intent} that identifies a service.
207     * </p>
208     * <p>
209     *      Notice that the parameters are different. You do not provide a
210     *      {@link android.content.ServiceConnection} object or the flags parameter. Instead,
211     *      you only provide the Intent. The method returns an object whose type is a
212     *      subclass of {@link android.os.IBinder}, or null if the method fails. An IBinder
213     *      object refers to a communication channel between the application and
214     *      the service. The flag is assumed to be {@link android.content.Context#BIND_AUTO_CREATE}.
215     * </p>
216     * <p>
217     *      See <a href="{@docRoot}guide/components/aidl.html">Designing a Remote Interface
218     *      Using AIDL</a> for more information about the communication channel object returned
219     *      by this method.
220     * </p>
221     * Note:  To be able to use bindService in a test, the service must implement getService()
222     * method. An example of this is in the ApiDemos sample application, in the
223     * LocalService demo.
224     *
225     * @param intent An Intent object of the form expected by
226     * {@link android.content.Context#bindService}.
227     *
228     * @return An object whose type is a subclass of IBinder, for making further calls into
229     * the service.
230     */
231    protected IBinder bindService(Intent intent) {
232        if (!mServiceAttached) {
233            setupService();
234        }
235        assertNotNull(mService);
236
237        if (!mServiceCreated) {
238            mService.onCreate();
239            mServiceCreated = true;
240        }
241        // no extras are expected by unbind
242        mServiceIntent = intent.cloneFilter();
243        IBinder result = mService.onBind(intent);
244
245        mServiceBound = true;
246        return result;
247    }
248
249    /**
250     * Makes the necessary calls to stop (or unbind) the service under test, and
251     * calls onDestroy().  Ordinarily this is called automatically (by {@link #tearDown}, but
252     * you can call it directly from your test in order to check for proper shutdown behavior.
253     */
254    protected void shutdownService() {
255        if (mServiceStarted) {
256            mService.stopSelf();
257            mServiceStarted = false;
258        } else if (mServiceBound) {
259            mService.onUnbind(mServiceIntent);
260            mServiceBound = false;
261        }
262        if (mServiceCreated) {
263            mService.onDestroy();
264            mServiceCreated = false;
265        }
266    }
267
268    /**
269     * <p>
270     *      Shuts down the service under test.  Ensures all resources are cleaned up and
271     *      garbage collected before moving on to the next test. This method is called after each
272     *      test method.
273     * </p>
274     * <p>
275     *      Subclasses that override this method must call <code>super.tearDown()</code> as their
276     *      last statement.
277     * </p>
278     *
279     * @throws Exception
280     */
281    @Override
282    protected void tearDown() throws Exception {
283        shutdownService();
284        mService = null;
285
286        // Scrub out members - protects against memory leaks in the case where someone
287        // creates a non-static inner class (thus referencing the test case) and gives it to
288        // someone else to hold onto
289        scrubClass(ServiceTestCase.class);
290
291        super.tearDown();
292    }
293
294    /**
295     * Sets the application that is used during the test.  If you do not call this method,
296     * a new {@link android.test.mock.MockApplication MockApplication} object is used.
297     *
298     * @param application The Application object that is used by the service under test.
299     *
300     * @see #getApplication()
301     */
302    public void setApplication(Application application) {
303        mApplication = application;
304    }
305
306    /**
307     * Returns the Application object in use by the service under test.
308     *
309     * @return The application object.
310     *
311     * @see #setApplication
312     */
313    public Application getApplication() {
314        return mApplication;
315    }
316
317    /**
318     * Returns the real system context that is saved by {@link #setUp()}. Use it to create
319     * mock or other types of context objects for the service under test.
320     *
321     * @return A normal system context.
322     */
323    public Context getSystemContext() {
324        return mSystemContext;
325    }
326
327    /**
328     * Tests that {@link #setupService()} runs correctly and issues an
329     * {@link junit.framework.Assert#assertNotNull(String, Object)} if it does.
330     * You can override this test method if you wish.
331     *
332     * @throws Exception
333     */
334    public void testServiceTestCaseSetUpProperly() throws Exception {
335        setupService();
336        assertNotNull("service should be launched successfully", mService);
337    }
338}
339