AndroidTestCase.java revision 54b6cfa9a9e5b861a9930af873580d6dc20f773c
1/* 2 * Copyright (C) 2006 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.content.Context; 20 21import java.lang.reflect.Field; 22 23import junit.framework.TestCase; 24 25/** 26 * Extend this if you need to access Resources or other things that depend on Activity Context. 27 */ 28public class AndroidTestCase extends TestCase { 29 30 protected Context mContext; 31 32 @Override 33 protected void setUp() throws Exception { 34 super.setUp(); 35 } 36 37 @Override 38 protected void tearDown() throws Exception { 39 super.tearDown(); 40 } 41 42 public void testAndroidTestCaseSetupProperly() { 43 assertNotNull("Context is null. setContext should be called before tests are run", 44 mContext); 45 } 46 47 public void setContext(Context context) { 48 mContext = context; 49 } 50 51 public Context getContext() { 52 return mContext; 53 } 54 55 /** 56 * This function is called by various TestCase implementations, at tearDown() time, in order 57 * to scrub out any class variables. This protects against memory leaks in the case where a 58 * test case creates a non-static inner class (thus referencing the test case) and gives it to 59 * someone else to hold onto. 60 * 61 * @param testCaseClass The class of the derived TestCase implementation. 62 * 63 * @throws IllegalAccessException 64 */ 65 protected void scrubClass(final Class<?> testCaseClass) 66 throws IllegalAccessException { 67 final Field[] fields = getClass().getDeclaredFields(); 68 for (Field field : fields) { 69 final Class<?> fieldClass = field.getDeclaringClass(); 70 if (testCaseClass.isAssignableFrom(fieldClass) && !field.getType().isPrimitive()) { 71 try { 72 field.setAccessible(true); 73 field.set(this, null); 74 } catch (Exception e) { 75 android.util.Log.d("TestCase", "Error: Could not nullify field!"); 76 } 77 78 if (field.get(this) != null) { 79 android.util.Log.d("TestCase", "Error: Could not nullify field!"); 80 } 81 } 82 } 83 } 84 85 86} 87