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.Activity; 20 21 import java.lang.reflect.Field; 22 import java.lang.reflect.Modifier; 23 24 /** 25 * This is common code used to support Activity test cases. For more useful classes, please see 26 * {@link android.test.ActivityUnitTestCase} and 27 * {@link android.test.ActivityInstrumentationTestCase}. 28 */ 29 public abstract class ActivityTestCase extends InstrumentationTestCase { 30 31 /** 32 * The activity that will be set up for use in each test method. 33 */ 34 private Activity mActivity; 35 36 /** 37 * @return Returns the activity under test. 38 */ getActivity()39 protected Activity getActivity() { 40 return mActivity; 41 } 42 43 /** 44 * Set the activity under test. 45 * @param testActivity The activity under test 46 */ setActivity(Activity testActivity)47 protected void setActivity(Activity testActivity) { 48 mActivity = testActivity; 49 } 50 51 /** 52 * This function is called by various TestCase implementations, at tearDown() time, in order 53 * to scrub out any class variables. This protects against memory leaks in the case where a 54 * test case creates a non-static inner class (thus referencing the test case) and gives it to 55 * someone else to hold onto. 56 * 57 * @param testCaseClass The class of the derived TestCase implementation. 58 * 59 * @throws IllegalAccessException 60 */ scrubClass(final Class<?> testCaseClass)61 protected void scrubClass(final Class<?> testCaseClass) 62 throws IllegalAccessException { 63 final Field[] fields = getClass().getDeclaredFields(); 64 for (Field field : fields) { 65 final Class<?> fieldClass = field.getDeclaringClass(); 66 if (testCaseClass.isAssignableFrom(fieldClass) && !field.getType().isPrimitive() 67 && (field.getModifiers() & Modifier.FINAL) == 0) { 68 try { 69 field.setAccessible(true); 70 field.set(this, null); 71 } catch (Exception e) { 72 android.util.Log.d("TestCase", "Error: Could not nullify field!"); 73 } 74 75 if (field.get(this) != null) { 76 android.util.Log.d("TestCase", "Error: Could not nullify field!"); 77 } 78 } 79 } 80 } 81 82 83 84 } 85