blob: cd54955f22fa6e9a54a639416e97a2c0ff97412a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.Context;
22import android.content.Intent;
23import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.test.mock.MockApplication;
25
Paul Duffin20af1df2018-01-05 13:52:17 +000026import android.test.mock.MockService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import 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
Joe Malin7d433aa2010-05-31 14:37:28 -070032 * Service, and hooks with which you can inject various dependencies and control
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033 * the environment in which your Service is tested.
34 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080035 * <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 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041 * <p><b>Lifecycle Support.</b>
Joe Malin7d433aa2010-05-31 14:37:28 -070042 * A Service is accessed with a specific sequence of
Scott Main7aee61f2011-02-08 11:25:01 -080043 * 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,
Joe Malin7d433aa2010-05-31 14:37:28 -070046 * <code>ServiceTestCase</code> enforces this protocol:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047 *
Joe Malin7d433aa2010-05-31 14:37:28 -070048 * <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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 * </ul>
Joe Malin7d433aa2010-05-31 14:37:28 -070076 *
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
Jeff Smitha45746e2012-07-19 14:19:24 -050092 * {@link android.test.mock.MockContext MockContext},
Joe Malin7d433aa2010-05-31 14:37:28 -070093 * {@link android.test.RenamingDelegatingContext RenamingDelegatingContext},
94 * {@link android.content.ContextWrapper ContextWrapper}, and
95 * {@link android.test.IsolatedContext}.
Stephan Linznerb51617f2016-01-27 18:09:50 -080096 *
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>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 */
Stephan Linznerb51617f2016-01-27 18:09:50 -0800102@Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103public abstract class ServiceTestCase<T extends Service> extends AndroidTestCase {
104
105 Class<T> mServiceClass;
106
107 private Context mSystemContext;
108 private Application mApplication;
109
Joe Malin7d433aa2010-05-31 14:37:28 -0700110 /**
111 * Constructor
112 * @param serviceClass The type of the service under test.
113 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 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 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700127 * @return An instance of the service under test. This instance is created automatically when
128 * a test calls {@link #startService} or {@link #bindService}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 */
130 public T getService() {
131 return mService;
132 }
133
134 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700135 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 */
141 @Override
142 protected void setUp() throws Exception {
143 super.setUp();
Joe Malin7d433aa2010-05-31 14:37:28 -0700144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 // get the real context, before the individual tests have a chance to muck with it
146 mSystemContext = getContext();
147
148 }
Joe Malin7d433aa2010-05-31 14:37:28 -0700149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700151 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 */
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 }
Paul Duffin20af1df2018-01-05 13:52:17 +0000167 MockService.attachForTesting(
168 mService, getContext(), mServiceClass.getName(), getApplication());
Joe Malin7d433aa2010-05-31 14:37:28 -0700169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 assertNotNull(mService);
Joe Malin7d433aa2010-05-31 14:37:28 -0700171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 mServiceId = new Random().nextInt();
173 mServiceAttached = true;
174 }
Joe Malin7d433aa2010-05-31 14:37:28 -0700175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700177 * 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)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 */
186 protected void startService(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 if (!mServiceAttached) {
188 setupService();
189 }
190 assertNotNull(mService);
Joe Malin7d433aa2010-05-31 14:37:28 -0700191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 if (!mServiceCreated) {
193 mService.onCreate();
194 mServiceCreated = true;
195 }
Evan Millar71be4b52010-06-01 13:55:50 -0700196 mService.onStartCommand(intent, 0, mServiceId);
Joe Malin7d433aa2010-05-31 14:37:28 -0700197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 mServiceStarted = true;
199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Joe Malin7d433aa2010-05-31 14:37:28 -0700201 /**
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>
Scott Main40eee612012-08-06 17:48:37 -0700217 * See <a href="{@docRoot}guide/components/aidl.html">Designing a Remote Interface
Joe Malin7d433aa2010-05-31 14:37:28 -0700218 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 */
231 protected IBinder bindService(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 if (!mServiceAttached) {
233 setupService();
234 }
235 assertNotNull(mService);
Joe Malin7d433aa2010-05-31 14:37:28 -0700236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 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);
Joe Malin7d433aa2010-05-31 14:37:28 -0700244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 mServiceBound = true;
246 return result;
247 }
Joe Malin7d433aa2010-05-31 14:37:28 -0700248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700250 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 */
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();
Mathew Inwood1804e252013-10-22 17:39:37 +0100264 mServiceCreated = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 }
266 }
Joe Malin7d433aa2010-05-31 14:37:28 -0700267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700269 * <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 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 * @throws Exception
280 */
281 @Override
282 protected void tearDown() throws Exception {
283 shutdownService();
284 mService = null;
285
Joe Malin7d433aa2010-05-31 14:37:28 -0700286 // Scrub out members - protects against memory leaks in the case where someone
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 // 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 }
Joe Malin7d433aa2010-05-31 14:37:28 -0700293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700295 * 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()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 */
302 public void setApplication(Application application) {
303 mApplication = application;
304 }
305
306 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700307 * Returns the Application object in use by the service under test.
308 *
309 * @return The application object.
310 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 * @see #setApplication
312 */
313 public Application getApplication() {
314 return mApplication;
315 }
Joe Malin7d433aa2010-05-31 14:37:28 -0700316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 /**
Joe Malin7d433aa2010-05-31 14:37:28 -0700318 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 */
323 public Context getSystemContext() {
324 return mSystemContext;
325 }
326
Joe Malin7d433aa2010-05-31 14:37:28 -0700327 /**
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 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 public void testServiceTestCaseSetUpProperly() throws Exception {
335 setupService();
336 assertNotNull("service should be launched successfully", mService);
337 }
338}