1 // Copyright 2017 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base; 6 7 import android.app.Application; 8 import android.content.ComponentCallbacks; 9 import android.content.ComponentCallbacks2; 10 import android.content.Context; 11 import android.content.res.Configuration; 12 import android.support.test.InstrumentationRegistry; 13 import android.support.test.filters.SmallTest; 14 15 import org.junit.Assert; 16 import org.junit.Test; 17 import org.junit.runner.RunWith; 18 19 import org.chromium.base.test.BaseJUnit4ClassRunner; 20 import org.chromium.base.test.util.AdvancedMockContext; 21 22 /** 23 * Tests for {@link org.chromium.base.test.util.AdvancedMockContext}. 24 */ 25 @RunWith(BaseJUnit4ClassRunner.class) 26 public class AdvancedMockContextTest { 27 private static class Callback1 implements ComponentCallbacks { 28 protected Configuration mConfiguration; 29 protected boolean mOnLowMemoryCalled; 30 31 @Override onConfigurationChanged(Configuration configuration)32 public void onConfigurationChanged(Configuration configuration) { 33 mConfiguration = configuration; 34 } 35 36 @Override onLowMemory()37 public void onLowMemory() { 38 mOnLowMemoryCalled = true; 39 } 40 } 41 42 private static class Callback2 extends Callback1 implements ComponentCallbacks2 { 43 private int mLevel; 44 45 @Override onTrimMemory(int level)46 public void onTrimMemory(int level) { 47 mLevel = level; 48 } 49 } 50 51 @Test 52 @SmallTest testComponentCallbacksForTargetContext()53 public void testComponentCallbacksForTargetContext() { 54 Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 55 Application targetApplication = (Application) targetContext.getApplicationContext(); 56 AdvancedMockContext context = new AdvancedMockContext(targetContext); 57 Callback1 callback1 = new Callback1(); 58 Callback2 callback2 = new Callback2(); 59 context.registerComponentCallbacks(callback1); 60 context.registerComponentCallbacks(callback2); 61 62 targetApplication.onLowMemory(); 63 Assert.assertTrue("onLowMemory should have been called.", callback1.mOnLowMemoryCalled); 64 Assert.assertTrue("onLowMemory should have been called.", callback2.mOnLowMemoryCalled); 65 66 Configuration configuration = new Configuration(); 67 targetApplication.onConfigurationChanged(configuration); 68 Assert.assertEquals("onConfigurationChanged should have been called.", configuration, 69 callback1.mConfiguration); 70 Assert.assertEquals("onConfigurationChanged should have been called.", configuration, 71 callback2.mConfiguration); 72 73 targetApplication.onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE); 74 Assert.assertEquals("onTrimMemory should have been called.", 75 ComponentCallbacks2.TRIM_MEMORY_MODERATE, callback2.mLevel); 76 } 77 } 78