Merge "Make Settings robotest work with tot Robolectric"

This commit is contained in:
James Lemieux
2018-11-01 05:48:14 +00:00
committed by Android (Google) Code Review
140 changed files with 706 additions and 823 deletions

View File

@@ -23,7 +23,6 @@ public class AppLocationPermissionPreferenceController extends
@Override @Override
public boolean isAvailable() { public boolean isAvailable() {
return Settings.Global.getInt(mContext.getContentResolver(), return Settings.Global.getInt(mContext.getContentResolver(),
android.provider.Settings.Global.LOCATION_SETTINGS_LINK_TO_PERMISSIONS_ENABLED, 1) Settings.Global.LOCATION_SETTINGS_LINK_TO_PERMISSIONS_ENABLED, 1) == 1;
== 1;
} }
} }

View File

@@ -37,6 +37,7 @@ public class CarrierPreferenceController extends BasePreferenceController {
public CarrierPreferenceController(Context context, String key) { public CarrierPreferenceController(Context context, String key) {
super(context, key); super(context, key);
mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
mCarrierConfigManager = new CarrierConfigManager(context); mCarrierConfigManager = new CarrierConfigManager(context);
mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
} }

View File

@@ -59,6 +59,7 @@ public class MobileDataPreferenceController extends TogglePreferenceController
public MobileDataPreferenceController(Context context, String key) { public MobileDataPreferenceController(Context context, String key) {
super(context, key); super(context, key);
mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
mSubscriptionManager = context.getSystemService(SubscriptionManager.class); mSubscriptionManager = context.getSystemService(SubscriptionManager.class);
mDataContentObserver = new DataContentObserver(new Handler(Looper.getMainLooper())); mDataContentObserver = new DataContentObserver(new Handler(Looper.getMainLooper()));
mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;

View File

@@ -82,7 +82,7 @@ public class MobileNetworkUtils {
* Returns true if Wifi calling is enabled for at least one phone. * Returns true if Wifi calling is enabled for at least one phone.
*/ */
public static boolean isWifiCallingEnabled(Context context) { public static boolean isWifiCallingEnabled(Context context) {
int phoneCount = TelephonyManager.from(context).getPhoneCount(); int phoneCount = context.getSystemService(TelephonyManager.class).getPhoneCount();
for (int i = 0; i < phoneCount; i++) { for (int i = 0; i < phoneCount; i++) {
if (isWifiCallingEnabled(context, i)) { if (isWifiCallingEnabled(context, i)) {
return true; return true;
@@ -218,7 +218,7 @@ public class MobileNetworkUtils {
*/ */
public static void setMobileDataEnabled(Context context, int subId, boolean enabled, public static void setMobileDataEnabled(Context context, int subId, boolean enabled,
boolean disableOtherSubscriptions) { boolean disableOtherSubscriptions) {
final TelephonyManager telephonyManager = TelephonyManager.from(context) final TelephonyManager telephonyManager = context.getSystemService(TelephonyManager.class)
.createForSubscriptionId(subId); .createForSubscriptionId(subId);
final SubscriptionManager subscriptionManager = context.getSystemService( final SubscriptionManager subscriptionManager = context.getSystemService(
SubscriptionManager.class); SubscriptionManager.class);
@@ -230,7 +230,7 @@ public class MobileNetworkUtils {
if (subInfoList != null) { if (subInfoList != null) {
for (SubscriptionInfo subInfo : subInfoList) { for (SubscriptionInfo subInfo : subInfoList) {
if (subInfo.getSubscriptionId() != subId) { if (subInfo.getSubscriptionId() != subId) {
TelephonyManager.from(context).createForSubscriptionId( context.getSystemService(TelephonyManager.class).createForSubscriptionId(
subInfo.getSubscriptionId()).setDataEnabled(false); subInfo.getSubscriptionId()).setDataEnabled(false);
} }
} }
@@ -245,7 +245,7 @@ public class MobileNetworkUtils {
if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) { if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
return false; return false;
} }
final TelephonyManager telephonyManager = TelephonyManager.from(context) final TelephonyManager telephonyManager = context.getSystemService(TelephonyManager.class)
.createForSubscriptionId(subId); .createForSubscriptionId(subId);
final PersistableBundle carrierConfig = context.getSystemService( final PersistableBundle carrierConfig = context.getSystemService(
CarrierConfigManager.class).getConfigForSubId(subId); CarrierConfigManager.class).getConfigForSubId(subId);
@@ -307,7 +307,7 @@ public class MobileNetworkUtils {
} }
private static boolean isGsmBasicOptions(Context context, int subId) { private static boolean isGsmBasicOptions(Context context, int subId) {
final TelephonyManager telephonyManager = TelephonyManager.from(context) final TelephonyManager telephonyManager = context.getSystemService(TelephonyManager.class)
.createForSubscriptionId(subId); .createForSubscriptionId(subId);
final PersistableBundle carrierConfig = context.getSystemService( final PersistableBundle carrierConfig = context.getSystemService(
CarrierConfigManager.class).getConfigForSubId(subId); CarrierConfigManager.class).getConfigForSubId(subId);
@@ -329,7 +329,7 @@ public class MobileNetworkUtils {
* settings * settings
*/ */
public static boolean isWorldMode(Context context, int subId) { public static boolean isWorldMode(Context context, int subId) {
final TelephonyManager telephonyManager = TelephonyManager.from(context) final TelephonyManager telephonyManager = context.getSystemService(TelephonyManager.class)
.createForSubscriptionId(subId); .createForSubscriptionId(subId);
boolean worldModeOn = false; boolean worldModeOn = false;
final String configString = context.getString(R.string.config_world_mode); final String configString = context.getString(R.string.config_world_mode);
@@ -392,7 +392,7 @@ public class MobileNetworkUtils {
Context con = context.createPackageContext("com.android.systemui", 0); Context con = context.createPackageContext("com.android.systemui", 0);
int id = con.getResources().getIdentifier("config_show4GForLTE", int id = con.getResources().getIdentifier("config_show4GForLTE",
"bool", "com.android.systemui"); "bool", "com.android.systemui");
return con.getResources().getBoolean(id); return con.getResources().getBoolean(id);
} catch (PackageManager.NameNotFoundException e) { } catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "NameNotFoundException for show4GFotLTE"); Log.e(TAG, "NameNotFoundException for show4GFotLTE");
return false; return false;
@@ -404,7 +404,7 @@ public class MobileNetworkUtils {
*/ */
public static boolean isTdscdmaSupported(Context context, int subId) { public static boolean isTdscdmaSupported(Context context, int subId) {
return isTdscdmaSupported(context, return isTdscdmaSupported(context,
TelephonyManager.from(context).createForSubscriptionId(subId)); context.getSystemService(TelephonyManager.class).createForSubscriptionId(subId));
} }
//TODO(b/117651939): move it to telephony //TODO(b/117651939): move it to telephony

View File

@@ -59,6 +59,7 @@ public class RoamingPreferenceController extends TogglePreferenceController impl
public RoamingPreferenceController(Context context, String key) { public RoamingPreferenceController(Context context, String key) {
super(context, key); super(context, key);
mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
mCarrierConfigManager = context.getSystemService(CarrierConfigManager.class); mCarrierConfigManager = context.getSystemService(CarrierConfigManager.class);
mDataContentObserver = new DataContentObserver(new Handler(Looper.getMainLooper())); mDataContentObserver = new DataContentObserver(new Handler(Looper.getMainLooper()));
mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;

View File

@@ -22,6 +22,7 @@ import android.net.Uri;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.provider.Settings; import android.provider.Settings;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import androidx.preference.Preference; import androidx.preference.Preference;
@@ -48,6 +49,7 @@ public abstract class CdmaBasePreferenceController extends BasePreferenceControl
public CdmaBasePreferenceController(Context context, String key) { public CdmaBasePreferenceController(Context context, String key) {
super(context, key); super(context, key);
mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
mDataContentObserver = new DataContentObserver(new Handler(Looper.getMainLooper())); mDataContentObserver = new DataContentObserver(new Handler(Looper.getMainLooper()));
} }

View File

@@ -28,7 +28,6 @@ import android.os.UserManager;
import android.util.Log; import android.util.Log;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceGroup;
import com.android.settingslib.RestrictedLockUtils; import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.core.AbstractPreferenceController; import com.android.settingslib.core.AbstractPreferenceController;
@@ -83,24 +82,6 @@ public abstract class NotificationPreferenceController extends AbstractPreferenc
return true; return true;
} }
// finds the preference recursively and removes it from its parent
private void findAndRemovePreference(PreferenceGroup prefGroup, String key) {
final int preferenceCount = prefGroup.getPreferenceCount();
for (int i = preferenceCount - 1; i >= 0; i--) {
final Preference preference = prefGroup.getPreference(i);
final String curKey = preference.getKey();
if (curKey != null && curKey.equals(key)) {
mPreference = preference;
prefGroup.removePreference(preference);
}
if (preference instanceof PreferenceGroup) {
findAndRemovePreference((PreferenceGroup) preference, key);
}
}
}
protected void onResume(NotificationBackend.AppRow appRow, protected void onResume(NotificationBackend.AppRow appRow,
@Nullable NotificationChannel channel, @Nullable NotificationChannelGroup group, @Nullable NotificationChannel channel, @Nullable NotificationChannelGroup group,
RestrictedLockUtils.EnforcedAdmin admin) { RestrictedLockUtils.EnforcedAdmin admin) {

View File

@@ -226,7 +226,7 @@ class SliceDataConverter {
SliceBuilderUtils.getPreferenceController(mContext, xmlSlice); SliceBuilderUtils.getPreferenceController(mContext, xmlSlice);
// Only add pre-approved Slices available on the device. // Only add pre-approved Slices available on the device.
if (controller.isAvailable() && controller.isSliceable()) { if (controller.isSliceable() && controller.isAvailable()) {
xmlSliceData.add(xmlSlice); xmlSliceData.add(xmlSlice);
} }
} }

View File

@@ -66,12 +66,11 @@ class SlicesIndexer implements Runnable {
return; return;
} }
SQLiteDatabase database = mHelper.getWritableDatabase(); final SQLiteDatabase database = mHelper.getWritableDatabase();
long startTime = System.currentTimeMillis();
database.beginTransaction();
try { try {
long startTime = System.currentTimeMillis();
database.beginTransaction();
mHelper.reconstruct(mHelper.getWritableDatabase()); mHelper.reconstruct(mHelper.getWritableDatabase());
List<SliceData> indexData = getSliceData(); List<SliceData> indexData = getSliceData();
insertSliceData(database, indexData); insertSliceData(database, indexData);
@@ -85,6 +84,7 @@ class SlicesIndexer implements Runnable {
} finally { } finally {
database.endTransaction(); database.endTransaction();
} }
database.close();
} }
@VisibleForTesting @VisibleForTesting

View File

@@ -68,7 +68,7 @@ public class WifiWakeupPreferenceController extends AbstractPreferenceController
@Override @Override
public boolean isAvailable() { public boolean isAvailable() {
return true; return true;
} }
@Override @Override
@@ -108,8 +108,8 @@ public class WifiWakeupPreferenceController extends AbstractPreferenceController
final SwitchPreference enableWifiWakeup = (SwitchPreference) preference; final SwitchPreference enableWifiWakeup = (SwitchPreference) preference;
enableWifiWakeup.setChecked(getWifiWakeupEnabled() enableWifiWakeup.setChecked(getWifiWakeupEnabled()
&& getWifiScanningEnabled() && getWifiScanningEnabled()
&& mLocationManager.isLocationEnabled()); && mLocationManager.isLocationEnabled());
if (!mLocationManager.isLocationEnabled()) { if (!mLocationManager.isLocationEnabled()) {
preference.setSummary(getNoLocationSummary()); preference.setSummary(getNoLocationSummary());
} else { } else {
@@ -117,7 +117,8 @@ public class WifiWakeupPreferenceController extends AbstractPreferenceController
} }
} }
@VisibleForTesting CharSequence getNoLocationSummary() { @VisibleForTesting
CharSequence getNoLocationSummary() {
AnnotationSpan.LinkInfo linkInfo = new AnnotationSpan.LinkInfo("link", null); AnnotationSpan.LinkInfo linkInfo = new AnnotationSpan.LinkInfo("link", null);
CharSequence locationText = mContext.getText(R.string.wifi_wakeup_summary_no_location); CharSequence locationText = mContext.getText(R.string.wifi_wakeup_summary_no_location);
return AnnotationSpan.linkify(locationText, linkInfo); return AnnotationSpan.linkify(locationText, linkInfo);

View File

@@ -23,6 +23,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.robolectric.RuntimeEnvironment.application; import static org.robolectric.RuntimeEnvironment.application;
import android.app.Activity;
import android.app.KeyguardManager; import android.app.KeyguardManager;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
@@ -35,6 +36,7 @@ import com.android.settingslib.RestrictedPreferenceHelper;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.Shadows; import org.robolectric.Shadows;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowKeyguardManager; import org.robolectric.shadows.ShadowKeyguardManager;
@@ -43,8 +45,8 @@ import org.robolectric.util.ReflectionHelpers;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config( @Config(
shadows = { shadows = {
ShadowUserManager.class, ShadowUserManager.class,
ShadowKeyguardManager.class, ShadowKeyguardManager.class,
}) })
public class RestrictedListPreferenceTest { public class RestrictedListPreferenceTest {
private static final int PROFILE_USER_ID = 11; private static final int PROFILE_USER_ID = 11;
@@ -52,6 +54,7 @@ public class RestrictedListPreferenceTest {
private static final int UNLAUNCHABLE_REASON_QUIET_MODE = 1; private static final int UNLAUNCHABLE_REASON_QUIET_MODE = 1;
private static final String EXTRA_UNLAUNCHABLE_REASON = "unlaunchable_reason"; private static final String EXTRA_UNLAUNCHABLE_REASON = "unlaunchable_reason";
private Activity mActivity;
private ShadowUserManager mShadowUserManager; private ShadowUserManager mShadowUserManager;
private ShadowKeyguardManager mShadowKeyguardManager; private ShadowKeyguardManager mShadowKeyguardManager;
private RestrictedListPreference mPreference; private RestrictedListPreference mPreference;
@@ -59,11 +62,12 @@ public class RestrictedListPreferenceTest {
@Before @Before
public void setUp() { public void setUp() {
mActivity = Robolectric.setupActivity(Activity.class);
mShadowKeyguardManager = mShadowKeyguardManager =
Shadows.shadowOf(application.getSystemService(KeyguardManager.class)); Shadows.shadowOf(application.getSystemService(KeyguardManager.class));
mMockHelper = mock(RestrictedPreferenceHelper.class); mMockHelper = mock(RestrictedPreferenceHelper.class);
mShadowUserManager = ShadowUserManager.getShadow(); mShadowUserManager = ShadowUserManager.getShadow();
mPreference = new RestrictedListPreference(application, mock(AttributeSet.class)); mPreference = new RestrictedListPreference(mActivity, mock(AttributeSet.class));
mPreference.setProfileUserId(PROFILE_USER_ID); mPreference.setProfileUserId(PROFILE_USER_ID);
ReflectionHelpers.setField(mPreference, "mHelper", mMockHelper); ReflectionHelpers.setField(mPreference, "mHelper", mMockHelper);
} }
@@ -80,7 +84,7 @@ public class RestrictedListPreferenceTest {
// Make sure that the performClick method on the helper is never reached. // Make sure that the performClick method on the helper is never reached.
verify(mMockHelper, never()).performClick(); verify(mMockHelper, never()).performClick();
// Assert that a CONFIRM_DEVICE_CREDENTIAL intent has been started. // Assert that a CONFIRM_DEVICE_CREDENTIAL intent has been started.
Intent started = Shadows.shadowOf(application).getNextStartedActivity(); Intent started = Shadows.shadowOf(mActivity).getNextStartedActivity();
assertThat(started.getExtras().getInt(Intent.EXTRA_USER_ID)).isEqualTo(PROFILE_USER_ID); assertThat(started.getExtras().getInt(Intent.EXTRA_USER_ID)).isEqualTo(PROFILE_USER_ID);
assertThat(started.getAction()) assertThat(started.getAction())
.isEqualTo(KeyguardManager.ACTION_CONFIRM_DEVICE_CREDENTIAL_WITH_USER); .isEqualTo(KeyguardManager.ACTION_CONFIRM_DEVICE_CREDENTIAL_WITH_USER);
@@ -95,7 +99,7 @@ public class RestrictedListPreferenceTest {
// Make sure that the performClick method on the helper is never reached. // Make sure that the performClick method on the helper is never reached.
verify(mMockHelper, never()).performClick(); verify(mMockHelper, never()).performClick();
// Assert that a new intent for enabling the work profile is started. // Assert that a new intent for enabling the work profile is started.
Intent started = Shadows.shadowOf(application).getNextStartedActivity(); Intent started = Shadows.shadowOf(mActivity).getNextStartedActivity();
Bundle extras = started.getExtras(); Bundle extras = started.getExtras();
int reason = extras.getInt(EXTRA_UNLAUNCHABLE_REASON); int reason = extras.getInt(EXTRA_UNLAUNCHABLE_REASON);
assertThat(reason).isEqualTo(UNLAUNCHABLE_REASON_QUIET_MODE); assertThat(reason).isEqualTo(UNLAUNCHABLE_REASON_QUIET_MODE);

View File

@@ -16,8 +16,6 @@
package com.android.settings; package com.android.settings;
import static com.android.settings.testutils.ResIdSubject.assertResId;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import android.content.Intent; import android.content.Intent;
@@ -33,7 +31,7 @@ import org.junit.runner.RunWith;
public class SetupWizardUtilsTest { public class SetupWizardUtilsTest {
@Test @Test
public void testCopySetupExtras() throws Throwable { public void testCopySetupExtras() {
Intent fromIntent = new Intent(); Intent fromIntent = new Intent();
final String theme = "TEST_THEME"; final String theme = "TEST_THEME";
fromIntent.putExtra(WizardManagerHelper.EXTRA_THEME, theme); fromIntent.putExtra(WizardManagerHelper.EXTRA_THEME, theme);
@@ -53,7 +51,7 @@ public class SetupWizardUtilsTest {
Intent intent = new Intent(); Intent intent = new Intent();
intent.putExtra(WizardManagerHelper.EXTRA_THEME, WizardManagerHelper.THEME_GLIF_V2); intent.putExtra(WizardManagerHelper.EXTRA_THEME, WizardManagerHelper.THEME_GLIF_V2);
assertResId(SetupWizardUtils.getTheme(intent)).isEqualTo(R.style.GlifV2Theme); assertThat(SetupWizardUtils.getTheme(intent)).isEqualTo(R.style.GlifV2Theme);
} }
@Test @Test
@@ -62,7 +60,7 @@ public class SetupWizardUtilsTest {
WizardManagerHelper.THEME_GLIF_V2_LIGHT); WizardManagerHelper.THEME_GLIF_V2_LIGHT);
Intent intent = new Intent(); Intent intent = new Intent();
assertResId(SetupWizardUtils.getTheme(intent)).isEqualTo(R.style.GlifV2Theme_Light); assertThat(SetupWizardUtils.getTheme(intent)).isEqualTo(R.style.GlifV2Theme_Light);
} }
@Test @Test
@@ -71,8 +69,8 @@ public class SetupWizardUtilsTest {
WizardManagerHelper.THEME_GLIF_V3_LIGHT); WizardManagerHelper.THEME_GLIF_V3_LIGHT);
Intent intent = new Intent(); Intent intent = new Intent();
assertResId(SetupWizardUtils.getTheme(intent)).isEqualTo(R.style.GlifV3Theme_Light); assertThat(SetupWizardUtils.getTheme(intent)).isEqualTo(R.style.GlifV3Theme_Light);
assertResId(SetupWizardUtils.getTransparentTheme(intent)) assertThat(SetupWizardUtils.getTransparentTheme(intent))
.isEqualTo(R.style.GlifV3Theme_Light_Transparent); .isEqualTo(R.style.GlifV3Theme_Light_Transparent);
} }
} }

View File

@@ -25,13 +25,13 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHearingAid; import android.bluetooth.BluetoothHearingAid;
import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
@@ -53,7 +53,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow; import org.robolectric.shadow.api.Shadow;
@@ -71,7 +71,7 @@ public class AccessibilityHearingAidPreferenceControllerTest {
private ShadowBluetoothAdapter mShadowBluetoothAdapter; private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private BluetoothManager mBluetoothManager; private BluetoothManager mBluetoothManager;
private BluetoothDevice mBluetoothDevice; private BluetoothDevice mBluetoothDevice;
private Context mContext; private Activity mContext;
private Preference mHearingAidPreference; private Preference mHearingAidPreference;
private AccessibilityHearingAidPreferenceController mPreferenceController; private AccessibilityHearingAidPreferenceController mPreferenceController;
@@ -89,7 +89,7 @@ public class AccessibilityHearingAidPreferenceControllerTest {
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
setupBluetoothEnvironment(); setupBluetoothEnvironment();
setupHearingAidEnvironment(); setupHearingAidEnvironment();
mHearingAidPreference = new Preference(mContext); mHearingAidPreference = new Preference(mContext);
@@ -145,8 +145,8 @@ public class AccessibilityHearingAidPreferenceControllerTest {
} }
@Test @Test
public void handleHearingAidPreferenceClick_withHearingAid_launchBluetoothDeviceDetailSetting() public void handleHearingAidPreferenceClick_withHearingAid_launchBluetoothDeviceDetailSetting
{ () {
mPreferenceController = spy(new AccessibilityHearingAidPreferenceController(mContext, mPreferenceController = spy(new AccessibilityHearingAidPreferenceController(mContext,
HEARING_AID_PREFERENCE)); HEARING_AID_PREFERENCE));
mPreferenceController.setPreference(mHearingAidPreference); mPreferenceController.setPreference(mHearingAidPreference);
@@ -161,7 +161,8 @@ public class AccessibilityHearingAidPreferenceControllerTest {
public void onNotSupportHearingAidProfile_doNotDoReceiverOperation() { public void onNotSupportHearingAidProfile_doNotDoReceiverOperation() {
//clear bluetooth supported profile //clear bluetooth supported profile
mShadowBluetoothAdapter.clearSupportedProfiles(); mShadowBluetoothAdapter.clearSupportedProfiles();
mPreferenceController = new AccessibilityHearingAidPreferenceController(mContext, HEARING_AID_PREFERENCE); mPreferenceController = new AccessibilityHearingAidPreferenceController(mContext,
HEARING_AID_PREFERENCE);
mPreferenceController.setPreference(mHearingAidPreference); mPreferenceController.setPreference(mHearingAidPreference);
//not call registerReceiver() //not call registerReceiver()
mPreferenceController.onResume(); mPreferenceController.onResume();

View File

@@ -59,7 +59,7 @@ public class ColorInversionPreferenceControllerTest {
@Test @Test
public void isChecked_enabled() { public void isChecked_enabled() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, ON); Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, ON);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -70,7 +70,7 @@ public class ColorInversionPreferenceControllerTest {
@Test @Test
public void isChecked_disabled() { public void isChecked_disabled() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, OFF); Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, OFF);
mController.updateState(mPreference); mController.updateState(mPreference);

View File

@@ -60,13 +60,13 @@ public class MagnificationGesturesPreferenceControllerTest {
@Test @Test
public void updateState_shouldRefreshSummary() { public void updateState_shouldRefreshSummary() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, ON); Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, ON);
mController.updateState(mPreference); mController.updateState(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.accessibility_feature_state_on)); .isEqualTo(mContext.getString(R.string.accessibility_feature_state_on));
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, OFF); Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, OFF);
mController.updateState(mPreference); mController.updateState(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
@@ -84,7 +84,7 @@ public class MagnificationGesturesPreferenceControllerTest {
@Test @Test
public void isChecked_enabled() { public void isChecked_enabled() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, ON); Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, ON);
assertThat(mController.isChecked()).isTrue(); assertThat(mController.isChecked()).isTrue();
@@ -92,7 +92,7 @@ public class MagnificationGesturesPreferenceControllerTest {
@Test @Test
public void isChecked_disabled() { public void isChecked_disabled() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, OFF); Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, OFF);
assertThat(mController.isChecked()).isFalse(); assertThat(mController.isChecked()).isFalse();

View File

@@ -85,13 +85,13 @@ public class MagnificationNavbarPreferenceControllerTest {
@Test @Test
public void updateState_shouldRefreshSummary() { public void updateState_shouldRefreshSummary() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, ON); Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, ON);
mController.updateState(mPreference); mController.updateState(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
.isEqualTo(mContext.getText(R.string.accessibility_feature_state_on)); .isEqualTo(mContext.getText(R.string.accessibility_feature_state_on));
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, OFF); Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, OFF);
mController.updateState(mPreference); mController.updateState(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
@@ -109,7 +109,7 @@ public class MagnificationNavbarPreferenceControllerTest {
@Test @Test
public void isChecked_enabled() { public void isChecked_enabled() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, ON); Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, ON);
assertThat(mController.isChecked()).isTrue(); assertThat(mController.isChecked()).isTrue();
@@ -117,7 +117,7 @@ public class MagnificationNavbarPreferenceControllerTest {
@Test @Test
public void isChecked_disabled() { public void isChecked_disabled() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, OFF); Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED, OFF);
assertThat(mController.isChecked()).isFalse(); assertThat(mController.isChecked()).isFalse();
@@ -151,7 +151,7 @@ public class MagnificationNavbarPreferenceControllerTest {
} }
@Implementation @Implementation
static boolean isApplicable(Resources res) { protected static boolean isApplicable(Resources res) {
return sIsApplicable; return sIsApplicable;
} }

View File

@@ -24,6 +24,7 @@ import static org.mockito.Mockito.when;
import android.accounts.Account; import android.accounts.Account;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.accounts.AuthenticatorDescription; import android.accounts.AuthenticatorDescription;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SyncAdapterType; import android.content.SyncAdapterType;
@@ -43,7 +44,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@@ -54,24 +55,24 @@ public class AccountSyncPreferenceControllerTest {
@Mock(answer = RETURNS_DEEP_STUBS) @Mock(answer = RETURNS_DEEP_STUBS)
private AccountManager mAccountManager; private AccountManager mAccountManager;
private Context mContext; private Activity mActivity;
private AccountSyncPreferenceController mController; private AccountSyncPreferenceController mController;
private Preference mPreference; private Preference mPreference;
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application; mActivity = Robolectric.setupActivity(Activity.class);
ShadowApplication.getInstance().setSystemService(Context.ACCOUNT_SERVICE, mAccountManager); ShadowApplication.getInstance().setSystemService(Context.ACCOUNT_SERVICE, mAccountManager);
when(mAccountManager.getAuthenticatorTypesAsUser(anyInt())).thenReturn( when(mAccountManager.getAuthenticatorTypesAsUser(anyInt())).thenReturn(
new AuthenticatorDescription[0]); new AuthenticatorDescription[0]);
when(mAccountManager.getAccountsAsUser(anyInt())).thenReturn(new Account[0]); when(mAccountManager.getAccountsAsUser(anyInt())).thenReturn(new Account[0]);
mPreference = new Preference(mContext); mPreference = new Preference(mActivity);
mPreference.setKey("account_sync"); mPreference.setKey("account_sync");
mController = new AccountSyncPreferenceController(mContext); mController = new AccountSyncPreferenceController(mActivity);
mController.init(new Account("acct1", "type1"), new UserHandle(3)); mController.init(new Account("acct1", "type1"), new UserHandle(3));
} }
@@ -102,7 +103,7 @@ public class AccountSyncPreferenceControllerTest {
mController.updateSummary(mPreference); mController.updateSummary(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.account_sync_summary_all_off)); .isEqualTo(mActivity.getString(R.string.account_sync_summary_all_off));
} }
@Test @Test
@@ -115,7 +116,7 @@ public class AccountSyncPreferenceControllerTest {
mController.updateSummary(mPreference); mController.updateSummary(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.account_sync_summary_all_off)); .isEqualTo(mActivity.getString(R.string.account_sync_summary_all_off));
} }
@Test @Test
@@ -129,7 +130,7 @@ public class AccountSyncPreferenceControllerTest {
mController.updateSummary(mPreference); mController.updateSummary(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.account_sync_summary_all_off)); .isEqualTo(mActivity.getString(R.string.account_sync_summary_all_off));
} }
@Test @Test
@@ -144,7 +145,7 @@ public class AccountSyncPreferenceControllerTest {
mController.updateSummary(mPreference); mController.updateSummary(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.account_sync_summary_all_off)); .isEqualTo(mActivity.getString(R.string.account_sync_summary_all_off));
} }
@Test @Test
@@ -157,7 +158,7 @@ public class AccountSyncPreferenceControllerTest {
mController.updateSummary(mPreference); mController.updateSummary(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.account_sync_summary_all_on)); .isEqualTo(mActivity.getString(R.string.account_sync_summary_all_on));
} }
@Test @Test
@@ -179,6 +180,6 @@ public class AccountSyncPreferenceControllerTest {
mController.updateSummary(mPreference); mController.updateSummary(mPreference);
assertThat(mPreference.getSummary()) assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.account_sync_summary_some_on, 3, 4)); .isEqualTo(mActivity.getString(R.string.account_sync_summary_some_on, 3, 4));
} }
} }

View File

@@ -25,6 +25,7 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo; import android.content.pm.ResolveInfo;
@@ -45,6 +46,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@@ -69,7 +71,7 @@ public class EmergencyInfoPreferenceControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mController = new EmergencyInfoPreferenceController(mContext); mController = new EmergencyInfoPreferenceController(mContext);
mPreference = new Preference(RuntimeEnvironment.application); mPreference = new Preference(Robolectric.setupActivity(Activity.class));
mPreference.setKey(mController.getPreferenceKey()); mPreference.setKey(mController.getPreferenceKey());
when(mScreen.findPreference(mPreference.getKey())).thenReturn(mPreference); when(mScreen.findPreference(mPreference.getKey())).thenReturn(mPreference);
} }
@@ -136,16 +138,16 @@ public class EmergencyInfoPreferenceControllerTest {
mController.updateState(preference); mController.updateState(preference);
verify(preference).setSummary( verify(preference).setSummary(
mContext.getString(R.string.emergency_info_summary, "user 1")); mContext.getString(R.string.emergency_info_summary, "user 1"));
} }
@Test @Test
public void handlePreferenceTreeClick_shouldStartActivity() { public void handlePreferenceTreeClick_shouldStartActivity() {
final ShadowApplication application = ShadowApplication.getInstance(); final ShadowApplication application = ShadowApplication.getInstance();
final Context context = RuntimeEnvironment.application; final Activity activity = Robolectric.setupActivity(Activity.class);
final Preference preference = new Preference(context); final Preference preference = new Preference(activity);
preference.setKey("emergency_info"); preference.setKey("emergency_info");
mController = new EmergencyInfoPreferenceController(context); mController = new EmergencyInfoPreferenceController(activity);
mController.handlePreferenceTreeClick(preference); mController.handlePreferenceTreeClick(preference);

View File

@@ -25,7 +25,6 @@ import static org.mockito.Mockito.when;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.UserManager;
import android.provider.Settings; import android.provider.Settings;
import androidx.preference.Preference; import androidx.preference.Preference;
@@ -36,7 +35,9 @@ import com.android.settings.applications.ProcStatsData;
import com.android.settings.applications.ProcessStatsDetail; import com.android.settings.applications.ProcessStatsDetail;
import com.android.settings.core.BasePreferenceController; import com.android.settings.core.BasePreferenceController;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.ShadowUserManager;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -44,11 +45,11 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = {ShadowUserManager.class})
public class AppMemoryPreferenceControllerTest { public class AppMemoryPreferenceControllerTest {
@Mock @Mock
@@ -67,8 +68,7 @@ public class AppMemoryPreferenceControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application; mContext = RuntimeEnvironment.application;
UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); ShadowUserManager.getShadow().setIsAdminUser(true);
Shadows.shadowOf(userManager).setIsAdminUser(true);
mController = mController =
spy(new AppMemoryPreferenceController(mContext, mFragment, null /* lifecycle */)); spy(new AppMemoryPreferenceController(mContext, mFragment, null /* lifecycle */));
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference); when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
@@ -77,6 +77,11 @@ public class AppMemoryPreferenceControllerTest {
when(mFragment.getActivity()).thenReturn(mActivity); when(mFragment.getActivity()).thenReturn(mActivity);
} }
@After
public void tearDown() {
ShadowUserManager.getShadow().reset();
}
@Test @Test
@Config(qualifiers = "mcc999") @Config(qualifiers = "mcc999")
public void getAvailabilityStatus_developmentSettingsEnabled_shouldReturnAvailable() { public void getAvailabilityStatus_developmentSettingsEnabled_shouldReturnAvailable() {
@@ -84,7 +89,7 @@ public class AppMemoryPreferenceControllerTest {
Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1); Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
assertThat(mController.getAvailabilityStatus()) assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE); .isEqualTo(BasePreferenceController.AVAILABLE);
} }
@Test @Test
@@ -93,7 +98,7 @@ public class AppMemoryPreferenceControllerTest {
Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1); Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
assertThat(mController.getAvailabilityStatus()) assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE); .isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
} }
@Test @Test
@@ -102,7 +107,7 @@ public class AppMemoryPreferenceControllerTest {
Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0); Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0);
assertThat(mController.getAvailabilityStatus()) assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE); .isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
} }
@Test @Test

View File

@@ -18,7 +18,7 @@ package com.android.settings.applications.appinfo;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import android.app.Application; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ActivityInfo; import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo; import android.content.pm.ResolveInfo;
@@ -32,6 +32,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows; import org.robolectric.Shadows;
import org.robolectric.shadows.ShadowPackageManager; import org.robolectric.shadows.ShadowPackageManager;
@@ -50,19 +51,19 @@ public class AppSettingPreferenceControllerTest {
@Mock @Mock
private AppInfoDashboardFragment mParent; private AppInfoDashboardFragment mParent;
private Application mApplication;
private ShadowPackageManager mPackageManager; private ShadowPackageManager mPackageManager;
private AppSettingPreferenceController mController; private AppSettingPreferenceController mController;
private Preference mPreference; private Preference mPreference;
private Activity mActivity;
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mApplication = RuntimeEnvironment.application; mActivity = Robolectric.setupActivity(Activity.class);
mPackageManager = Shadows.shadowOf(mApplication.getPackageManager()); mPackageManager = Shadows.shadowOf(RuntimeEnvironment.application.getPackageManager());
mController = new AppSettingPreferenceController(mApplication, "test_key"); mController = new AppSettingPreferenceController(mActivity, "test_key");
mController.setPackageName(TEST_PKG_NAME).setParentFragment(mParent); mController.setPackageName(TEST_PKG_NAME).setParentFragment(mParent);
mPreference = new Preference(mApplication); mPreference = new Preference(mActivity);
mPreference.setKey(mController.getPreferenceKey()); mPreference.setKey(mController.getPreferenceKey());
} }
@@ -108,7 +109,7 @@ public class AppSettingPreferenceControllerTest {
mPackageManager.addResolveInfoForIntent(RESOLVED_INTENT, info); mPackageManager.addResolveInfoForIntent(RESOLVED_INTENT, info);
assertThat(mController.handlePreferenceTreeClick(mPreference)).isTrue(); assertThat(mController.handlePreferenceTreeClick(mPreference)).isTrue();
assertThat(Shadows.shadowOf(mApplication).getNextStartedActivity().getComponent()) assertThat(Shadows.shadowOf(mActivity).getNextStartedActivity().getComponent())
.isEqualTo(TEST_INTENT.getComponent()); .isEqualTo(TEST_INTENT.getComponent());
} }
} }

View File

@@ -23,11 +23,11 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.os.UserManager; import android.os.UserManager;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
@@ -39,7 +39,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class DefaultAppShortcutPreferenceControllerBaseTest { public class DefaultAppShortcutPreferenceControllerBaseTest {
@@ -49,19 +49,17 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
@Mock @Mock
private AppInfoDashboardFragment mFragment; private AppInfoDashboardFragment mFragment;
@Mock @Mock
private PreferenceScreen mScreen;
@Mock
private Preference mPreference; private Preference mPreference;
private Context mContext; private Activity mActivity;
private TestPreferenceController mController; private TestPreferenceController mController;
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mActivity = spy(Robolectric.setupActivity(Activity.class));
when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager); when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
mController = new TestPreferenceController(mContext, mFragment); mController = new TestPreferenceController(mActivity, mFragment);
final String key = mController.getPreferenceKey(); final String key = mController.getPreferenceKey();
when(mPreference.getKey()).thenReturn(key); when(mPreference.getKey()).thenReturn(key);
} }
@@ -95,7 +93,7 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
mController.isDefault = true; mController.isDefault = true;
mController.updateState(mPreference); mController.updateState(mPreference);
String yesString = mContext.getString(R.string.yes); String yesString = mActivity.getString(R.string.yes);
verify(mPreference).setSummary(yesString); verify(mPreference).setSummary(yesString);
} }
@@ -105,7 +103,7 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
mController.updateState(mPreference); mController.updateState(mPreference);
String noString = mContext.getString(R.string.no); String noString = mActivity.getString(R.string.no);
verify(mPreference).setSummary(noString); verify(mPreference).setSummary(noString);
} }
@@ -113,7 +111,7 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
public void handlePreferenceTreeClick_shouldStartDefaultAppSettings() { public void handlePreferenceTreeClick_shouldStartDefaultAppSettings() {
mController.handlePreferenceTreeClick(mPreference); mController.handlePreferenceTreeClick(mPreference);
verify(mContext).startActivity(argThat(intent -> intent != null verify(mActivity).startActivity(argThat(intent -> intent != null
&& intent.getStringExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT).equals( && intent.getStringExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT).equals(
DefaultAppSettings.class.getName()) DefaultAppSettings.class.getName())
&& intent.getBundleExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS) && intent.getBundleExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS)

View File

@@ -17,6 +17,7 @@
package com.android.settings.applications.appinfo; package com.android.settings.applications.appinfo;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doAnswer;
@@ -29,12 +30,14 @@ import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo; import android.content.pm.PackageInfo;
import android.os.UserHandle; import android.os.UserHandle;
import android.os.UserManager; import android.os.UserManager;
import com.android.settings.applications.AppStateInstallAppsBridge; import com.android.settings.applications.AppStateInstallAppsBridge;
import com.android.settings.applications.AppStateInstallAppsBridge.InstallAppsState; import com.android.settings.applications.AppStateInstallAppsBridge.InstallAppsState;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settingslib.RestrictedPreferenceHelper; import com.android.settingslib.RestrictedPreferenceHelper;
import com.android.settingslib.RestrictedSwitchPreference; import com.android.settingslib.RestrictedSwitchPreference;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -135,7 +138,7 @@ public class ExternalSourcesDetailsTest {
assertThat(fragment.refreshUi()).isTrue(); assertThat(fragment.refreshUi()).isTrue();
// Assertions // Assertions
assertThat(shadowUserManager.hasUserRestriction( assertThat(userManager.hasUserRestriction(
UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
UserHandle.of(UserHandle.myUserId()))).isTrue(); UserHandle.of(UserHandle.myUserId()))).isTrue();
assertThat(mSwitchPref.isDisabledByAdmin()).isTrue(); assertThat(mSwitchPref.isDisabledByAdmin()).isTrue();
@@ -174,7 +177,7 @@ public class ExternalSourcesDetailsTest {
assertThat(fragment.refreshUi()).isTrue(); assertThat(fragment.refreshUi()).isTrue();
// Assertions // Assertions
assertThat(shadowUserManager.hasUserRestriction( assertThat(userManager.hasUserRestriction(
UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY,
UserHandle.of(UserHandle.myUserId()))).isTrue(); UserHandle.of(UserHandle.myUserId()))).isTrue();
assertThat(mSwitchPref.isDisabledByAdmin()).isTrue(); assertThat(mSwitchPref.isDisabledByAdmin()).isTrue();
@@ -215,10 +218,10 @@ public class ExternalSourcesDetailsTest {
assertThat(fragment.refreshUi()).isTrue(); assertThat(fragment.refreshUi()).isTrue();
// Assertions // Assertions
assertThat(shadowUserManager.hasUserRestriction( assertThat(userManager.hasUserRestriction(
UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY,
UserHandle.of(UserHandle.myUserId()))).isTrue(); UserHandle.of(UserHandle.myUserId()))).isTrue();
assertThat(shadowUserManager.hasUserRestriction( assertThat(userManager.hasUserRestriction(
UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
UserHandle.of(UserHandle.myUserId()))).isTrue(); UserHandle.of(UserHandle.myUserId()))).isTrue();
assertThat(mSwitchPref.isDisabledByAdmin()).isTrue(); assertThat(mSwitchPref.isDisabledByAdmin()).isTrue();

View File

@@ -62,13 +62,13 @@ public class InstantAppAccountPreferenceControllerTest {
mContext = spy(RuntimeEnvironment.application); mContext = spy(RuntimeEnvironment.application);
when(mContext.getPackageManager()).thenReturn(mPackageManager); when(mContext.getPackageManager()).thenReturn(mPackageManager);
mContentResolver = mContext.getContentResolver(); mContentResolver = mContext.getContentResolver();
mEnableEphemeralFeature = Settings.Secure.getInt(mContentResolver, mEnableEphemeralFeature = Settings.Global.getInt(mContentResolver,
ENABLE_EPHEMERAL_FEATURE, 1); ENABLE_EPHEMERAL_FEATURE, 1);
} }
@After @After
public void tearDown() { public void tearDown() {
Settings.Secure.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, Settings.Global.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE,
mEnableEphemeralFeature); mEnableEphemeralFeature);
} }
@@ -81,10 +81,10 @@ public class InstantAppAccountPreferenceControllerTest {
} }
@Test @Test
public void testGetAvailabilityStatus_enableWebActiions() { public void testGetAvailabilityStatus_enableWebActions() {
when(mPackageManager.getInstantAppResolverSettingsComponent()).thenReturn(mComponentName); when(mPackageManager.getInstantAppResolverSettingsComponent()).thenReturn(mComponentName);
mController = new InstantAppAccountPreferenceController(mContext, PREF_KEY); mController = new InstantAppAccountPreferenceController(mContext, PREF_KEY);
Settings.Secure.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, 1); Settings.Global.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, 1);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE); assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
} }
@@ -93,7 +93,7 @@ public class InstantAppAccountPreferenceControllerTest {
public void testGetAvailabilityStatus_disableWebActions() { public void testGetAvailabilityStatus_disableWebActions() {
when(mPackageManager.getInstantAppResolverSettingsComponent()).thenReturn(mComponentName); when(mPackageManager.getInstantAppResolverSettingsComponent()).thenReturn(mComponentName);
mController = new InstantAppAccountPreferenceController(mContext, PREF_KEY); mController = new InstantAppAccountPreferenceController(mContext, PREF_KEY);
Settings.Secure.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, 0); Settings.Global.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, 0);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE); assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
} }

View File

@@ -57,26 +57,26 @@ public class InstantAppWebActionPreferenceControllerTest {
mContentResolver = mContext.getContentResolver(); mContentResolver = mContext.getContentResolver();
mController = new InstantAppWebActionPreferenceController(mContext, PREF_KEY); mController = new InstantAppWebActionPreferenceController(mContext, PREF_KEY);
mSwitchPreference = new SwitchPreference(mContext); mSwitchPreference = new SwitchPreference(mContext);
mEnableEphemeralFeature = Settings.Secure.getInt(mContentResolver, mEnableEphemeralFeature = Settings.Global.getInt(mContentResolver,
ENABLE_EPHEMERAL_FEATURE, 1); ENABLE_EPHEMERAL_FEATURE, 1);
} }
@After @After
public void tearDown() { public void tearDown() {
Settings.Secure.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, Settings.Global.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE,
mEnableEphemeralFeature); mEnableEphemeralFeature);
} }
@Test @Test
public void testGetAvailabilityStatus_enableWebActions() { public void testGetAvailabilityStatus_enableWebActions() {
Settings.Secure.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, 1); Settings.Global.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, 1);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE); assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
} }
@Test @Test
public void testGetAvailabilityStatus_disableWebActions() { public void testGetAvailabilityStatus_disableWebActions() {
Settings.Secure.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, 0); Settings.Global.putInt(mContentResolver, ENABLE_EPHEMERAL_FEATURE, 0);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE); assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
} }

View File

@@ -19,18 +19,13 @@ package com.android.settings.biometrics.fingerprint;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.robolectric.RuntimeEnvironment.application;
import android.content.Intent; import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager; import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.EnrollmentCallback; import android.hardware.fingerprint.FingerprintManager.EnrollmentCallback;
import android.media.AudioAttributes;
import android.os.CancellationSignal; import android.os.CancellationSignal;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.widget.TextView; import android.widget.TextView;
import com.android.settings.R; import com.android.settings.R;
@@ -39,7 +34,7 @@ import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.SettingsShadowResourcesImpl; import com.android.settings.testutils.shadow.SettingsShadowResourcesImpl;
import com.android.settings.testutils.shadow.ShadowUtils; import com.android.settings.testutils.shadow.ShadowUtils;
import com.android.settings.testutils.shadow.ShadowVibrator;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@@ -50,15 +45,11 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric; import org.robolectric.Robolectric;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import java.util.concurrent.TimeUnit;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = { @Config(shadows = {
SettingsShadowResourcesImpl.class, SettingsShadowResourcesImpl.class,
ShadowUtils.class, ShadowUtils.class})
ShadowVibrator.class})
public class FingerprintEnrollEnrollingTest { public class FingerprintEnrollEnrollingTest {
@Mock @Mock
@@ -70,7 +61,6 @@ public class FingerprintEnrollEnrollingTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
ShadowUtils.setFingerprintManager(mFingerprintManager); ShadowUtils.setFingerprintManager(mFingerprintManager);
ShadowVibrator.addToServiceMap();
FakeFeatureFactory.setupForTest(); FakeFeatureFactory.setupForTest();
mActivity = Robolectric.buildActivity( mActivity = Robolectric.buildActivity(
@@ -84,11 +74,10 @@ public class FingerprintEnrollEnrollingTest {
@After @After
public void tearDown() { public void tearDown() {
ShadowUtils.reset(); ShadowUtils.reset();
ShadowVibrator.reset();
} }
@Test @Test
public void fingerprintEnrollHelp_shouldShowHelpTextAndVibrate() { public void fingerprintEnrollHelp_shouldShowHelpText() {
EnrollmentCallback enrollmentCallback = verifyAndCaptureEnrollmentCallback(); EnrollmentCallback enrollmentCallback = verifyAndCaptureEnrollmentCallback();
enrollmentCallback.onEnrollmentProgress(123); enrollmentCallback.onEnrollmentProgress(123);
@@ -98,17 +87,6 @@ public class FingerprintEnrollEnrollingTest {
TextView errorText = mActivity.findViewById(R.id.error_text); TextView errorText = mActivity.findViewById(R.id.error_text);
assertThat(errorText.getText()).isEqualTo("test enrollment help"); assertThat(errorText.getText()).isEqualTo("test enrollment help");
Robolectric.getForegroundThreadScheduler().advanceBy(2, TimeUnit.MILLISECONDS);
ShadowVibrator shadowVibrator =
Shadow.extract(application.getSystemService(Vibrator.class));
verify(shadowVibrator.delegate).vibrate(
anyInt(),
nullable(String.class),
any(VibrationEffect.class),
nullable(String.class),
nullable(AudioAttributes.class));
} }
private EnrollmentCallback verifyAndCaptureEnrollmentCallback() { private EnrollmentCallback verifyAndCaptureEnrollmentCallback() {

View File

@@ -73,7 +73,6 @@ public class SetupFingerprintEnrollIntroductionTest {
Shadows.shadowOf(application.getPackageManager()) Shadows.shadowOf(application.getPackageManager())
.setSystemFeature(PackageManager.FEATURE_FINGERPRINT, true); .setSystemFeature(PackageManager.FEATURE_FINGERPRINT, true);
ShadowFingerprintManager.addToServiceMap();
FakeFeatureFactory.setupForTest(); FakeFeatureFactory.setupForTest();
@@ -86,7 +85,6 @@ public class SetupFingerprintEnrollIntroductionTest {
@After @After
public void tearDown() { public void tearDown() {
ShadowStorageManager.reset(); ShadowStorageManager.reset();
ShadowFingerprintManager.reset();
} }
@Test @Test

View File

@@ -26,18 +26,14 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = {ShadowBluetoothAdapter.class})
public class AlwaysDiscoverableTest { public class AlwaysDiscoverableTest {
@Mock @Mock
@@ -45,14 +41,12 @@ public class AlwaysDiscoverableTest {
private AlwaysDiscoverable mAlwaysDiscoverable; private AlwaysDiscoverable mAlwaysDiscoverable;
private BluetoothAdapter mBluetoothAdapter; private BluetoothAdapter mBluetoothAdapter;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mAlwaysDiscoverable = new AlwaysDiscoverable(mContext); mAlwaysDiscoverable = new AlwaysDiscoverable(mContext);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
} }
@Test @Test
@@ -82,7 +76,7 @@ public class AlwaysDiscoverableTest {
@Test @Test
public void startSetsModeAndRegistersReceiver() { public void startSetsModeAndRegistersReceiver() {
mShadowBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_NONE); mBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_NONE);
mAlwaysDiscoverable.start(); mAlwaysDiscoverable.start();
assertThat(mBluetoothAdapter.getScanMode()) assertThat(mBluetoothAdapter.getScanMode())
.isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE); .isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
@@ -110,7 +104,7 @@ public class AlwaysDiscoverableTest {
} }
private void sendScanModeChangedIntent(int newMode, int previousMode) { private void sendScanModeChangedIntent(int newMode, int previousMode) {
mShadowBluetoothAdapter.setScanMode(newMode); mBluetoothAdapter.setScanMode(newMode);
Intent intent = new Intent(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); Intent intent = new Intent(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_SCAN_MODE, newMode); intent.putExtra(BluetoothAdapter.EXTRA_SCAN_MODE, newMode);
intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, previousMode); intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, previousMode);

View File

@@ -38,6 +38,7 @@ import com.android.settings.testutils.shadow.SettingsShadowResourcesImpl;
import com.android.settings.testutils.shadow.ShadowAlertDialogCompat; import com.android.settings.testutils.shadow.ShadowAlertDialogCompat;
import com.android.settingslib.bluetooth.CachedBluetoothDevice; import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider; import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.testutils.DrawableTestHelper;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -79,7 +80,7 @@ public class BluetoothDevicePreferenceTest {
mPreference.onClicked(); mPreference.onClicked();
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_DISCONNECT); .action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_DISCONNECT);
} }
@Test @Test
@@ -90,7 +91,7 @@ public class BluetoothDevicePreferenceTest {
mPreference.onClicked(); mPreference.onClicked();
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_CONNECT); .action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_CONNECT);
} }
@Test @Test
@@ -103,9 +104,10 @@ public class BluetoothDevicePreferenceTest {
mPreference.onClicked(); mPreference.onClicked();
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR); .action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR);
verify(mMetricsFeatureProvider, never()) verify(mMetricsFeatureProvider, never())
.action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR_DEVICES_WITHOUT_NAMES); .action(mContext,
MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR_DEVICES_WITHOUT_NAMES);
} }
@Test @Test
@@ -118,9 +120,10 @@ public class BluetoothDevicePreferenceTest {
mPreference.onClicked(); mPreference.onClicked();
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR); .action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR);
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action(mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR_DEVICES_WITHOUT_NAMES); .action(mContext,
MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR_DEVICES_WITHOUT_NAMES);
} }
@Test @Test
@@ -164,13 +167,12 @@ public class BluetoothDevicePreferenceTest {
@Test @Test
public void imagingDeviceIcon_isICSettingsPrint() { public void imagingDeviceIcon_isICSettingsPrint() {
when(mCachedBluetoothDevice.getBatteryLevel()) when(mCachedBluetoothDevice.getBatteryLevel())
.thenReturn(BluetoothDevice.BATTERY_LEVEL_UNKNOWN); .thenReturn(BluetoothDevice.BATTERY_LEVEL_UNKNOWN);
when(mCachedBluetoothDevice.getBtClass()) when(mCachedBluetoothDevice.getBtClass())
.thenReturn(new BluetoothClass(BluetoothClass.Device.Major.IMAGING)); .thenReturn(new BluetoothClass(BluetoothClass.Device.Major.IMAGING));
mPreference.onDeviceAttributesChanged(); mPreference.onDeviceAttributesChanged();
assertThat(mPreference.getIcon()).isEqualTo( DrawableTestHelper.assertDrawableResId(mPreference.getIcon(), R.drawable.ic_settings_print);
mContext.getDrawable(R.drawable.ic_settings_print));
} }
@Test @Test

View File

@@ -32,6 +32,7 @@ import androidx.preference.Preference;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.dashboard.DashboardFragment; import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settingslib.testutils.DrawableTestHelper;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -72,10 +73,10 @@ public class BluetoothPairingPreferenceControllerTest {
Preference pref = mController.createBluetoothPairingPreference(ORDER); Preference pref = mController.createBluetoothPairingPreference(ORDER);
assertThat(pref.getKey()).isEqualTo(BluetoothPairingPreferenceController.KEY_PAIRING); assertThat(pref.getKey()).isEqualTo(BluetoothPairingPreferenceController.KEY_PAIRING);
assertThat(pref.getIcon()).isEqualTo(mContext.getDrawable(R.drawable.ic_menu_add)); DrawableTestHelper.assertDrawableResId(pref.getIcon(), R.drawable.ic_menu_add);
assertThat(pref.getOrder()).isEqualTo(ORDER); assertThat(pref.getOrder()).isEqualTo(ORDER);
assertThat(pref.getTitle()) assertThat(pref.getTitle())
.isEqualTo(mContext.getString(R.string.bluetooth_pairing_pref_title)); .isEqualTo(mContext.getString(R.string.bluetooth_pairing_pref_title));
} }
@Test @Test

View File

@@ -49,7 +49,6 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows; import org.robolectric.Shadows;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
import java.util.ArrayList; import java.util.ArrayList;
@@ -75,7 +74,6 @@ public class DiscoverableFooterPreferenceControllerTest {
private DiscoverableFooterPreferenceController mDiscoverableFooterPreferenceController; private DiscoverableFooterPreferenceController mDiscoverableFooterPreferenceController;
private BroadcastReceiver mBluetoothChangedReceiver; private BroadcastReceiver mBluetoothChangedReceiver;
private ShadowApplication mShadowApplication; private ShadowApplication mShadowApplication;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
@Before @Before
public void setUp() { public void setUp() {
@@ -91,7 +89,6 @@ public class DiscoverableFooterPreferenceControllerTest {
mAlwaysDiscoverable); mAlwaysDiscoverable);
mBluetoothChangedReceiver = mDiscoverableFooterPreferenceController mBluetoothChangedReceiver = mDiscoverableFooterPreferenceController
.mBluetoothChangedReceiver; .mBluetoothChangedReceiver;
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
} }
@Test @Test
@@ -137,15 +134,15 @@ public class DiscoverableFooterPreferenceControllerTest {
@Test @Test
public void onBluetoothStateChanged_bluetoothOn_updateTitle() { public void onBluetoothStateChanged_bluetoothOn_updateTitle() {
mShadowBluetoothAdapter.setName(DEVICE_NAME); BluetoothAdapter.getDefaultAdapter().setName(DEVICE_NAME);
sendBluetoothStateChangedIntent(BluetoothAdapter.STATE_ON); sendBluetoothStateChangedIntent(BluetoothAdapter.STATE_ON);
assertThat(mPreference.getTitle()).isEqualTo(generateTitle(DEVICE_NAME)); assertThat(mPreference.getTitle()).isEqualTo(generateTitle(DEVICE_NAME));
} }
@Test @Test
public void onBluetoothStateChanged_bluetoothOff_updateTitle(){ public void onBluetoothStateChanged_bluetoothOff_updateTitle() {
mShadowBluetoothAdapter.setName(DEVICE_NAME); BluetoothAdapter.getDefaultAdapter().setName(DEVICE_NAME);
sendBluetoothStateChangedIntent(BluetoothAdapter.STATE_OFF); sendBluetoothStateChangedIntent(BluetoothAdapter.STATE_OFF);
assertThat(mPreference.getTitle()).isEqualTo(generateTitle(null)); assertThat(mPreference.getTitle()).isEqualTo(generateTitle(null));

View File

@@ -28,6 +28,7 @@ import com.android.settings.R;
import com.android.settings.connecteddevice.DevicePreferenceCallback; import com.android.settings.connecteddevice.DevicePreferenceCallback;
import com.android.settings.dashboard.DashboardFragment; import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settingslib.testutils.DrawableTestHelper;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -68,8 +69,8 @@ public class ConnectedUsbDeviceUpdaterTest {
mDeviceUpdater.initUsbPreference(mContext); mDeviceUpdater.initUsbPreference(mContext);
assertThat(mDeviceUpdater.mUsbPreference.getTitle()).isEqualTo("USB"); assertThat(mDeviceUpdater.mUsbPreference.getTitle()).isEqualTo("USB");
assertThat(mDeviceUpdater.mUsbPreference.getIcon()) DrawableTestHelper.assertDrawableResId(
.isEqualTo(mContext.getDrawable(R.drawable.ic_usb)); mDeviceUpdater.mUsbPreference.getIcon(), R.drawable.ic_usb);
assertThat(mDeviceUpdater.mUsbPreference.isSelectable()).isTrue(); assertThat(mDeviceUpdater.mUsbPreference.isSelectable()).isTrue();
} }

View File

@@ -16,10 +16,12 @@
package com.android.settings.connecteddevice.usb; package com.android.settings.connecteddevice.usb;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.content.Context; import android.content.Context;
import android.graphics.drawable.Drawable;
import android.hardware.usb.UsbManager; import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbPort; import android.hardware.usb.UsbPort;
@@ -34,12 +36,14 @@ import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.ShadowEntityHeaderController; import com.android.settings.testutils.shadow.ShadowEntityHeaderController;
import com.android.settings.widget.EntityHeaderController; import com.android.settings.widget.EntityHeaderController;
import com.android.settingslib.core.lifecycle.Lifecycle; import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.testutils.DrawableTestHelper;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Answers; import org.mockito.Answers;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
@@ -100,7 +104,10 @@ public class UsbDetailsHeaderControllerTest {
mDetailsHeaderController.refresh(true, UsbManager.FUNCTION_NONE, UsbPort.POWER_ROLE_SINK, mDetailsHeaderController.refresh(true, UsbManager.FUNCTION_NONE, UsbPort.POWER_ROLE_SINK,
UsbPort.DATA_ROLE_DEVICE); UsbPort.DATA_ROLE_DEVICE);
verify(mHeaderController).setLabel(mContext.getString(R.string.usb_pref)); verify(mHeaderController).setLabel(mContext.getString(R.string.usb_pref));
verify(mHeaderController).setIcon(mContext.getDrawable(R.drawable.ic_usb)); verify(mHeaderController).setIcon(argThat((ArgumentMatcher<Drawable>) t -> {
DrawableTestHelper.assertDrawableResId(t, R.drawable.ic_usb);
return true;
}));
verify(mHeaderController).done(mActivity, true); verify(mHeaderController).done(mActivity, true);
} }
} }

View File

@@ -24,6 +24,7 @@ import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -56,7 +57,7 @@ public class InstrumentedDialogFragmentTest {
// Precondition: no metrics feature // Precondition: no metrics feature
assertThat(fragment.getMetricsFeatureProvider()).isNull(); assertThat(fragment.getMetricsFeatureProvider()).isNull();
fragment.onAttach(ShadowApplication.getInstance().getApplicationContext()); fragment.onAttach(RuntimeEnvironment.application);
// Verify: has metrics feature // Verify: has metrics feature
assertThat(fragment.getMetricsFeatureProvider()).isNotNull(); assertThat(fragment.getMetricsFeatureProvider()).isNotNull();

View File

@@ -157,8 +157,7 @@ public class CategoryManagerTest {
mCategoryByKeyMap.put(CATEGORY_HOMEPAGE, category); mCategoryByKeyMap.put(CATEGORY_HOMEPAGE, category);
// Sort their priorities // Sort their priorities
mCategoryManager.sortCategories(ShadowApplication.getInstance().getApplicationContext(), mCategoryManager.sortCategories(RuntimeEnvironment.application, mCategoryByKeyMap);
mCategoryByKeyMap);
// Verify they are now sorted. // Verify they are now sorted.
assertThat(category.getTile(0)).isSameAs(tile3); assertThat(category.getTile(0)).isSameAs(tile3);

View File

@@ -75,7 +75,6 @@ import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows; import org.robolectric.Shadows;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity; import org.robolectric.shadows.ShadowActivity;
import org.robolectric.shadows.ShadowApplication;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList; import java.util.ArrayList;
@@ -348,8 +347,7 @@ public class DashboardFeatureProviderImplTest {
ReflectionHelpers.setField( ReflectionHelpers.setField(
mImpl, "mPackageManager", RuntimeEnvironment.application.getPackageManager()); mImpl, "mPackageManager", RuntimeEnvironment.application.getPackageManager());
FragmentActivity activity = Robolectric.buildActivity(FragmentActivity.class).get(); FragmentActivity activity = Robolectric.buildActivity(FragmentActivity.class).get();
final ShadowApplication application = ShadowApplication.getInstance(); final Preference preference = new Preference(RuntimeEnvironment.application);
final Preference preference = new Preference(application.getApplicationContext());
final Tile tile = new Tile(mActivityInfo, CategoryKey.CATEGORY_HOMEPAGE); final Tile tile = new Tile(mActivityInfo, CategoryKey.CATEGORY_HOMEPAGE);
mActivityInfo.metaData.putString(META_DATA_PREFERENCE_KEYHINT, "key"); mActivityInfo.metaData.putString(META_DATA_PREFERENCE_KEYHINT, "key");
mActivityInfo.metaData.putString("com.android.settings.intent.action", "TestAction"); mActivityInfo.metaData.putString("com.android.settings.intent.action", "TestAction");

View File

@@ -22,8 +22,8 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.net.NetworkTemplate; import android.net.NetworkTemplate;
@@ -51,7 +51,6 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric; import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows; import org.robolectric.Shadows;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity; import org.robolectric.shadows.ShadowActivity;
@@ -66,7 +65,7 @@ public class DataUsageSummaryPreferenceTest {
private static final long UPDATE_LAG_MILLIS = 10000000L; private static final long UPDATE_LAG_MILLIS = 10000000L;
private static final String DUMMY_CARRIER = "z-mobile"; private static final String DUMMY_CARRIER = "z-mobile";
private Context mContext; private Activity mActivity;
private PreferenceViewHolder mHolder; private PreferenceViewHolder mHolder;
private DataUsageSummaryPreference mSummaryPreference; private DataUsageSummaryPreference mSummaryPreference;
private TextView mUsageTitle; private TextView mUsageTitle;
@@ -87,9 +86,9 @@ public class DataUsageSummaryPreferenceTest {
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mActivity = spy(Robolectric.setupActivity(Activity.class));
mSummaryPreference = new DataUsageSummaryPreference(mContext, null /* attrs */); mSummaryPreference = new DataUsageSummaryPreference(mActivity, null /* attrs */);
LayoutInflater inflater = LayoutInflater.from(mContext); LayoutInflater inflater = LayoutInflater.from(mActivity);
View view = inflater.inflate(mSummaryPreference.getLayoutResource(), null /* root */, View view = inflater.inflate(mSummaryPreference.getLayoutResource(), null /* root */,
false /* attachToRoot */); false /* attachToRoot */);
@@ -227,7 +226,7 @@ public class DataUsageSummaryPreferenceTest {
bindViewHolder(); bindViewHolder();
assertThat(mCarrierInfo.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mCarrierInfo.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(mCarrierInfo.getCurrentTextColor()).isEqualTo( assertThat(mCarrierInfo.getCurrentTextColor()).isEqualTo(
Utils.getColorAttrDefaultColor(mContext, android.R.attr.textColorSecondary)); Utils.getColorAttrDefaultColor(mActivity, android.R.attr.textColorSecondary));
assertThat(mCarrierInfo.getTypeface()).isEqualTo(Typeface.SANS_SERIF); assertThat(mCarrierInfo.getTypeface()).isEqualTo(Typeface.SANS_SERIF);
} }
@@ -240,7 +239,7 @@ public class DataUsageSummaryPreferenceTest {
bindViewHolder(); bindViewHolder();
assertThat(mCarrierInfo.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mCarrierInfo.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(mCarrierInfo.getCurrentTextColor()).isEqualTo( assertThat(mCarrierInfo.getCurrentTextColor()).isEqualTo(
Utils.getColorAttrDefaultColor(mContext, android.R.attr.colorError)); Utils.getColorAttrDefaultColor(mActivity, android.R.attr.colorError));
assertThat(mCarrierInfo.getTypeface()).isEqualTo( assertThat(mCarrierInfo.getTypeface()).isEqualTo(
DataUsageSummaryPreference.SANS_SERIF_MEDIUM); DataUsageSummaryPreference.SANS_SERIF_MEDIUM);
} }
@@ -273,7 +272,7 @@ public class DataUsageSummaryPreferenceTest {
bindViewHolder(); bindViewHolder();
assertThat(mCycleTime.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mCycleTime.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(mCycleTime.getText()).isEqualTo( assertThat(mCycleTime.getText()).isEqualTo(
mContext.getString(R.string.billing_cycle_less_than_one_day_left)); mActivity.getString(R.string.billing_cycle_less_than_one_day_left));
} }
@Test @Test
@@ -285,7 +284,7 @@ public class DataUsageSummaryPreferenceTest {
bindViewHolder(); bindViewHolder();
assertThat(mCycleTime.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mCycleTime.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(mCycleTime.getText()).isEqualTo( assertThat(mCycleTime.getText()).isEqualTo(
mContext.getString(R.string.billing_cycle_none_left)); mActivity.getString(R.string.billing_cycle_none_left));
} }
@Test @Test
@@ -384,7 +383,7 @@ public class DataUsageSummaryPreferenceTest {
assertThat(mDataUsed.getText().toString()).isEqualTo("1.00 MB used"); assertThat(mDataUsed.getText().toString()).isEqualTo("1.00 MB used");
assertThat(mDataRemaining.getText().toString()).isEqualTo("9.00 MB left"); assertThat(mDataRemaining.getText().toString()).isEqualTo("9.00 MB left");
assertThat(mDataRemaining.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mDataRemaining.getVisibility()).isEqualTo(View.VISIBLE);
final int colorId = Utils.getColorAttrDefaultColor(mContext, android.R.attr.colorAccent); final int colorId = Utils.getColorAttrDefaultColor(mActivity, android.R.attr.colorAccent);
assertThat(mDataRemaining.getCurrentTextColor()).isEqualTo(colorId); assertThat(mDataRemaining.getCurrentTextColor()).isEqualTo(colorId);
} }
@@ -400,7 +399,7 @@ public class DataUsageSummaryPreferenceTest {
bindViewHolder(); bindViewHolder();
assertThat(mDataUsed.getText().toString()).isEqualTo("11.00 MB used"); assertThat(mDataUsed.getText().toString()).isEqualTo("11.00 MB used");
assertThat(mDataRemaining.getText().toString()).isEqualTo("1.00 MB over"); assertThat(mDataRemaining.getText().toString()).isEqualTo("1.00 MB over");
final int colorId = Utils.getColorAttrDefaultColor(mContext, android.R.attr.colorError); final int colorId = Utils.getColorAttrDefaultColor(mActivity, android.R.attr.colorError);
assertThat(mDataRemaining.getCurrentTextColor()).isEqualTo(colorId); assertThat(mDataRemaining.getCurrentTextColor()).isEqualTo(colorId);
} }
@@ -429,7 +428,7 @@ public class DataUsageSummaryPreferenceTest {
bindViewHolder(); bindViewHolder();
assertThat(mLaunchButton.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mLaunchButton.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(mLaunchButton.getText()) assertThat(mLaunchButton.getText())
.isEqualTo(mContext.getString(R.string.launch_mdp_app_text)); .isEqualTo(mActivity.getString(R.string.launch_mdp_app_text));
mLaunchButton.callOnClick(); mLaunchButton.callOnClick();
ShadowActivity shadowActivity = Shadows.shadowOf(activity); ShadowActivity shadowActivity = Shadows.shadowOf(activity);
@@ -443,12 +442,12 @@ public class DataUsageSummaryPreferenceTest {
@Test @Test
public void testSetUsageInfo_withOverflowStrings_dataRemainingNotShown() { public void testSetUsageInfo_withOverflowStrings_dataRemainingNotShown() {
LayoutInflater inflater = LayoutInflater.from(mContext); LayoutInflater inflater = LayoutInflater.from(mActivity);
View view = inflater.inflate(mSummaryPreference.getLayoutResource(), null /* root */, View view = inflater.inflate(mSummaryPreference.getLayoutResource(), null /* root */,
false /* attachToRoot */); false /* attachToRoot */);
TextView dataUsed = spy(new TextView(mContext)); TextView dataUsed = spy(new TextView(mActivity));
TextView dataRemaining = spy(new TextView(mContext)); TextView dataRemaining = spy(new TextView(mActivity));
doReturn(dataUsed).when(mHolder).findViewById(R.id.data_usage_view); doReturn(dataUsed).when(mHolder).findViewById(R.id.data_usage_view);
doReturn(dataRemaining).when(mHolder).findViewById(R.id.data_remaining_view); doReturn(dataRemaining).when(mHolder).findViewById(R.id.data_remaining_view);
@@ -459,10 +458,10 @@ public class DataUsageSummaryPreferenceTest {
10 * BillingCycleSettings.MIB_IN_BYTES, 10 * BillingCycleSettings.MIB_IN_BYTES,
true /* hasMobileData */); true /* hasMobileData */);
when(mContext.getResources()).thenCallRealMethod(); when(mActivity.getResources()).thenCallRealMethod();
when(mContext.getText(R.string.data_used_formatted)) when(mActivity.getText(R.string.data_used_formatted))
.thenReturn("^1 ^2 used with long trailing text"); .thenReturn("^1 ^2 used with long trailing text");
when(mContext.getText(R.string.data_remaining)).thenReturn("^1 left"); when(mActivity.getText(R.string.data_remaining)).thenReturn("^1 left");
bindViewHolder(); bindViewHolder();
@@ -497,7 +496,7 @@ public class DataUsageSummaryPreferenceTest {
bindViewHolder(); bindViewHolder();
assertThat(mUsageTitle.getText().toString()) assertThat(mUsageTitle.getText().toString())
.isEqualTo(mContext.getString(R.string.data_usage_wifi_title)); .isEqualTo(mActivity.getString(R.string.data_usage_wifi_title));
assertThat(mUsageTitle.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mUsageTitle.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(mCycleTime.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mCycleTime.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(mCycleTime.getText()).isEqualTo(cycleText); assertThat(mCycleTime.getText()).isEqualTo(cycleText);
@@ -505,7 +504,7 @@ public class DataUsageSummaryPreferenceTest {
assertThat(mDataLimits.getVisibility()).isEqualTo(View.GONE); assertThat(mDataLimits.getVisibility()).isEqualTo(View.GONE);
assertThat(mLaunchButton.getVisibility()).isEqualTo(View.VISIBLE); assertThat(mLaunchButton.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(mLaunchButton.getText()) assertThat(mLaunchButton.getText())
.isEqualTo(mContext.getString(R.string.launch_wifi_text)); .isEqualTo(mActivity.getString(R.string.launch_wifi_text));
mLaunchButton.callOnClick(); mLaunchButton.callOnClick();
ShadowActivity shadowActivity = Shadows.shadowOf(activity); ShadowActivity shadowActivity = Shadows.shadowOf(activity);

View File

@@ -39,23 +39,27 @@ import com.android.settings.testutils.shadow.SettingsShadowResources;
import com.android.settings.testutils.shadow.SettingsShadowResourcesImpl; import com.android.settings.testutils.shadow.SettingsShadowResourcesImpl;
import com.android.settings.testutils.shadow.ShadowDashboardFragment; import com.android.settings.testutils.shadow.ShadowDashboardFragment;
import com.android.settings.testutils.shadow.ShadowDataUsageUtils; import com.android.settings.testutils.shadow.ShadowDataUsageUtils;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settings.testutils.shadow.ShadowUtils; import com.android.settings.testutils.shadow.ShadowUtils;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric; import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@Config(shadows = { @Config(shadows = {
SettingsShadowResourcesImpl.class, SettingsShadowResourcesImpl.class,
SettingsShadowResources.SettingsShadowTheme.class, SettingsShadowResources.SettingsShadowTheme.class,
ShadowUtils.class, ShadowUtils.class,
ShadowDataUsageUtils.class, ShadowDataUsageUtils.class,
ShadowDashboardFragment.class ShadowDashboardFragment.class,
ShadowUserManager.class,
}) })
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class DataUsageSummaryTest { public class DataUsageSummaryTest {
@@ -77,15 +81,21 @@ public class DataUsageSummaryTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
ShadowApplication shadowContext = ShadowApplication.getInstance(); ShadowApplication shadowContext = ShadowApplication.getInstance();
ShadowUserManager.getShadow().setIsAdminUser(true);
shadowContext.setSystemService(Context.NETWORK_POLICY_SERVICE, mNetworkPolicyManager); shadowContext.setSystemService(Context.NETWORK_POLICY_SERVICE, mNetworkPolicyManager);
mContext = shadowContext.getApplicationContext(); mContext = RuntimeEnvironment.application;
mActivity = spy(Robolectric.buildActivity(FragmentActivity.class).get()); mActivity = spy(Robolectric.buildActivity(FragmentActivity.class).get());
mSummaryProvider = DataUsageSummary.SUMMARY_PROVIDER_FACTORY mSummaryProvider = DataUsageSummary.SUMMARY_PROVIDER_FACTORY
.createSummaryProvider(mActivity, mSummaryLoader); .createSummaryProvider(mActivity, mSummaryLoader);
} }
@After
public void tearDown() {
ShadowUserManager.getShadow().reset();
}
@Test @Test
public void formatUsage_shouldLookLikeFormatFileSize() { public void formatUsage_shouldLookLikeFormatFileSize() {
SettingsShadowResources.overrideResource(com.android.internal.R.string.fileSizeSuffix, SettingsShadowResources.overrideResource(com.android.internal.R.string.fileSizeSuffix,

View File

@@ -39,6 +39,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -57,7 +58,7 @@ public final class DataUsageUtilsTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
ShadowApplication shadowContext = ShadowApplication.getInstance(); ShadowApplication shadowContext = ShadowApplication.getInstance();
mContext = shadowContext.getApplicationContext(); mContext = RuntimeEnvironment.application;
shadowContext.setSystemService(Context.CONNECTIVITY_SERVICE, mManager); shadowContext.setSystemService(Context.CONNECTIVITY_SERVICE, mManager);
shadowContext.setSystemService(Context.TELEPHONY_SERVICE, mTelephonyManager); shadowContext.setSystemService(Context.TELEPHONY_SERVICE, mTelephonyManager);
shadowContext.setSystemService(Context.NETWORK_STATS_SERVICE, mNetworkStatsManager); shadowContext.setSystemService(Context.NETWORK_STATS_SERVICE, mNetworkStatsManager);
@@ -109,6 +110,6 @@ public final class DataUsageUtilsTest {
DataUsageUtils.hasEthernet(mContext); DataUsageUtils.hasEthernet(mContext);
verify(mNetworkStatsManager).querySummaryForUser(eq(ConnectivityManager.TYPE_ETHERNET), verify(mNetworkStatsManager).querySummaryForUser(eq(ConnectivityManager.TYPE_ETHERNET),
eq(subscriber), anyLong() /* startTime */, anyLong() /* endTime */); eq(subscriber), anyLong() /* startTime */, anyLong() /* endTime */);
} }
} }

View File

@@ -68,7 +68,7 @@ public class AdbPreferenceControllerTest {
@Test @Test
public void onDeveloperOptionsDisabled_shouldDisablePreference() { public void onDeveloperOptionsDisabled_shouldDisablePreference() {
mController.onDeveloperOptionsDisabled(); mController.onDeveloperOptionsDisabled();
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.ADB_ENABLED, -1); Settings.Global.ADB_ENABLED, -1);
assertThat(mode).isEqualTo(AdbPreferenceController.ADB_SETTING_OFF); assertThat(mode).isEqualTo(AdbPreferenceController.ADB_SETTING_OFF);
@@ -79,7 +79,7 @@ public class AdbPreferenceControllerTest {
@Test @Test
public void onAdbDialogConfirmed_shouldEnableAdbSetting() { public void onAdbDialogConfirmed_shouldEnableAdbSetting() {
mController.onAdbDialogConfirmed(); mController.onAdbDialogConfirmed();
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.ADB_ENABLED, -1); Settings.Global.ADB_ENABLED, -1);
assertThat(mode).isEqualTo(AdbPreferenceController.ADB_SETTING_ON); assertThat(mode).isEqualTo(AdbPreferenceController.ADB_SETTING_ON);
@@ -87,7 +87,7 @@ public class AdbPreferenceControllerTest {
@Test @Test
public void onAdbDialogDismissed_preferenceShouldNotBeChecked() { public void onAdbDialogDismissed_preferenceShouldNotBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.ADB_ENABLED, Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.ADB_ENABLED,
AdbPreferenceController.ADB_SETTING_OFF); AdbPreferenceController.ADB_SETTING_OFF);
mController.onAdbDialogDismissed(); mController.onAdbDialogDismissed();

View File

@@ -25,6 +25,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.content.Context; import android.content.Context;
import android.os.SystemProperties;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import androidx.preference.SwitchPreference; import androidx.preference.SwitchPreference;
@@ -37,7 +38,6 @@ import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowSystemProperties;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class BluetoothDeviceNoNamePreferenceControllerTest { public class BluetoothDeviceNoNamePreferenceControllerTest {
@@ -56,7 +56,7 @@ public class BluetoothDeviceNoNamePreferenceControllerTest {
mContext = RuntimeEnvironment.application; mContext = RuntimeEnvironment.application;
mController = new BluetoothDeviceNoNamePreferenceController(mContext); mController = new BluetoothDeviceNoNamePreferenceController(mContext);
when(mPreferenceScreen.findPreference(mController.getPreferenceKey())) when(mPreferenceScreen.findPreference(mController.getPreferenceKey()))
.thenReturn(mPreference); .thenReturn(mPreference);
mController.displayPreference(mPreferenceScreen); mController.displayPreference(mPreferenceScreen);
} }
@@ -64,8 +64,9 @@ public class BluetoothDeviceNoNamePreferenceControllerTest {
public void onPreferenceChanged_settingEnabled_shouldTurnOnBluetoothDeviceNoName() { public void onPreferenceChanged_settingEnabled_shouldTurnOnBluetoothDeviceNoName() {
mController.onPreferenceChange(mPreference, true /* new value */); mController.onPreferenceChange(mPreference, true /* new value */);
final boolean mode = ShadowSystemProperties final boolean mode = SystemProperties.getBoolean(
.native_get_boolean(BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY, false /* default */); BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY,
false /* default */);
assertThat(mode).isTrue(); assertThat(mode).isTrue();
} }
@@ -74,16 +75,16 @@ public class BluetoothDeviceNoNamePreferenceControllerTest {
public void onPreferenceChanged_settingDisabled_shouldTurnOffBluetoothDeviceNoName() { public void onPreferenceChanged_settingDisabled_shouldTurnOffBluetoothDeviceNoName() {
mController.onPreferenceChange(mPreference, false /* new value */); mController.onPreferenceChange(mPreference, false /* new value */);
final boolean mode = ShadowSystemProperties final boolean mode = SystemProperties.getBoolean(
.native_get_boolean(BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY, true /* default */); BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY, true /* default */);
assertThat(mode).isFalse(); assertThat(mode).isFalse();
} }
@Test @Test
public void updateState_settingEnabled_preferenceShouldBeChecked() { public void updateState_settingEnabled_preferenceShouldBeChecked() {
ShadowSystemProperties SystemProperties.set(BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY,
.native_set(BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY, Boolean.toString(true)); Boolean.toString(true));
mController.updateState(mPreference); mController.updateState(mPreference);
verify(mPreference).setChecked(true); verify(mPreference).setChecked(true);
@@ -91,8 +92,8 @@ public class BluetoothDeviceNoNamePreferenceControllerTest {
@Test @Test
public void updateState_settingDisabled_preferenceShouldNotBeChecked() { public void updateState_settingDisabled_preferenceShouldNotBeChecked() {
ShadowSystemProperties SystemProperties.set(BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY,
.native_set(BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY, Boolean.toString(false)); Boolean.toString(false));
mController.updateState(mPreference); mController.updateState(mPreference);
verify(mPreference).setChecked(false); verify(mPreference).setChecked(false);
@@ -102,8 +103,9 @@ public class BluetoothDeviceNoNamePreferenceControllerTest {
public void onDeveloperOptionsDisabled_shouldDisablePreference() { public void onDeveloperOptionsDisabled_shouldDisablePreference() {
mController.onDeveloperOptionsDisabled(); mController.onDeveloperOptionsDisabled();
final boolean mode = ShadowSystemProperties final boolean mode = SystemProperties.getBoolean(
.native_get_boolean(BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY, true /* default */); BLUETOOTH_SHOW_DEVICES_WITHOUT_NAMES_PROPERTY,
true /* default */);
assertThat(mode).isFalse(); assertThat(mode).isFalse();
verify(mPreference).setEnabled(false); verify(mPreference).setEnabled(false);

View File

@@ -61,7 +61,7 @@ public class DebugViewAttributesPreferenceControllerTest {
public void onPreferenceChanged_turnOnViewAttributes() { public void onPreferenceChanged_turnOnViewAttributes() {
mController.onPreferenceChange(null, true); mController.onPreferenceChange(null, true);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.DEBUG_VIEW_ATTRIBUTES, -1); Settings.Global.DEBUG_VIEW_ATTRIBUTES, -1);
assertThat(mode).isEqualTo(DebugViewAttributesPreferenceController.SETTING_VALUE_ON); assertThat(mode).isEqualTo(DebugViewAttributesPreferenceController.SETTING_VALUE_ON);
@@ -71,7 +71,7 @@ public class DebugViewAttributesPreferenceControllerTest {
public void onPreferenceChanged_turnOffViewAttributes() { public void onPreferenceChanged_turnOffViewAttributes() {
mController.onPreferenceChange(null, false); mController.onPreferenceChange(null, false);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.DEBUG_VIEW_ATTRIBUTES, -1); Settings.Global.DEBUG_VIEW_ATTRIBUTES, -1);
assertThat(mode).isEqualTo(DebugViewAttributesPreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(DebugViewAttributesPreferenceController.SETTING_VALUE_OFF);
@@ -79,7 +79,7 @@ public class DebugViewAttributesPreferenceControllerTest {
@Test @Test
public void updateState_preferenceShouldBeChecked() { public void updateState_preferenceShouldBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.DEBUG_VIEW_ATTRIBUTES, Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.DEBUG_VIEW_ATTRIBUTES,
DebugViewAttributesPreferenceController.SETTING_VALUE_ON); DebugViewAttributesPreferenceController.SETTING_VALUE_ON);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -88,7 +88,7 @@ public class DebugViewAttributesPreferenceControllerTest {
@Test @Test
public void updateState_preferenceShouldNotBeChecked() { public void updateState_preferenceShouldNotBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.DEBUG_VIEW_ATTRIBUTES, Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.DEBUG_VIEW_ATTRIBUTES,
DebugViewAttributesPreferenceController.SETTING_VALUE_OFF); DebugViewAttributesPreferenceController.SETTING_VALUE_OFF);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -98,7 +98,7 @@ public class DebugViewAttributesPreferenceControllerTest {
@Test @Test
public void onDeveloperOptionsDisabled_shouldDisablePreference() { public void onDeveloperOptionsDisabled_shouldDisablePreference() {
mController.onDeveloperOptionsDisabled(); mController.onDeveloperOptionsDisabled();
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.DEBUG_VIEW_ATTRIBUTES, -1); Settings.Global.DEBUG_VIEW_ATTRIBUTES, -1);
assertThat(mode).isEqualTo(DebugViewAttributesPreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(DebugViewAttributesPreferenceController.SETTING_VALUE_OFF);

View File

@@ -25,7 +25,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.content.Context; import android.content.Context;
import android.os.UserManager;
import android.provider.SearchIndexableResource; import android.provider.SearchIndexableResource;
import android.provider.Settings; import android.provider.Settings;
@@ -33,6 +32,7 @@ import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.SettingsShadowResources; import com.android.settings.testutils.shadow.SettingsShadowResources;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settings.widget.SwitchBar; import com.android.settings.widget.SwitchBar;
import com.android.settings.widget.ToggleSwitch; import com.android.settings.widget.ToggleSwitch;
import com.android.settingslib.development.AbstractEnableAdbPreferenceController; import com.android.settingslib.development.AbstractEnableAdbPreferenceController;
@@ -44,16 +44,15 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements; import org.robolectric.annotation.Implements;
import org.robolectric.shadows.ShadowUserManager;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
import java.util.List; import java.util.List;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = ShadowUserManager.class)
public class DevelopmentSettingsDashboardFragmentTest { public class DevelopmentSettingsDashboardFragmentTest {
private ToggleSwitch mSwitch; private ToggleSwitch mSwitch;
@@ -69,14 +68,14 @@ public class DevelopmentSettingsDashboardFragmentTest {
mSwitch = switchBar.getSwitch(); mSwitch = switchBar.getSwitch();
mDashboard = spy(new DevelopmentSettingsDashboardFragment()); mDashboard = spy(new DevelopmentSettingsDashboardFragment());
ReflectionHelpers.setField(mDashboard, "mSwitchBar", switchBar); ReflectionHelpers.setField(mDashboard, "mSwitchBar", switchBar);
UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); mShadowUserManager = ShadowUserManager.getShadow();
mShadowUserManager = Shadows.shadowOf(userManager);
mShadowUserManager.setIsAdminUser(true); mShadowUserManager.setIsAdminUser(true);
} }
@After @After
public void tearDown() { public void tearDown() {
ShadowEnableDevelopmentSettingWarningDialog.reset(); ShadowEnableDevelopmentSettingWarningDialog.reset();
mShadowUserManager.reset();
} }
@Test @Test
@@ -87,7 +86,7 @@ public class DevelopmentSettingsDashboardFragmentTest {
@Test @Test
public void shouldLogAsFeatureFlagPage() { public void shouldLogAsFeatureFlagPage() {
assertThat(mDashboard.getMetricsCategory()) assertThat(mDashboard.getMetricsCategory())
.isEqualTo(MetricsProto.MetricsEvent.DEVELOPMENT); .isEqualTo(MetricsProto.MetricsEvent.DEVELOPMENT);
} }
@Test @Test
@@ -184,7 +183,7 @@ public class DevelopmentSettingsDashboardFragmentTest {
public void onOemUnlockDialogConfirmed_shouldCallControllerOemConfirmed() { public void onOemUnlockDialogConfirmed_shouldCallControllerOemConfirmed() {
final OemUnlockPreferenceController controller = mock(OemUnlockPreferenceController.class); final OemUnlockPreferenceController controller = mock(OemUnlockPreferenceController.class);
doReturn(controller).when(mDashboard) doReturn(controller).when(mDashboard)
.getDevelopmentOptionsController(OemUnlockPreferenceController.class); .getDevelopmentOptionsController(OemUnlockPreferenceController.class);
mDashboard.onOemUnlockDialogConfirmed(); mDashboard.onOemUnlockDialogConfirmed();
verify(controller).onOemUnlockConfirmed(); verify(controller).onOemUnlockConfirmed();
} }
@@ -193,7 +192,7 @@ public class DevelopmentSettingsDashboardFragmentTest {
public void onOemUnlockDialogConfirmed_shouldCallControllerOemDismissed() { public void onOemUnlockDialogConfirmed_shouldCallControllerOemDismissed() {
final OemUnlockPreferenceController controller = mock(OemUnlockPreferenceController.class); final OemUnlockPreferenceController controller = mock(OemUnlockPreferenceController.class);
doReturn(controller).when(mDashboard) doReturn(controller).when(mDashboard)
.getDevelopmentOptionsController(OemUnlockPreferenceController.class); .getDevelopmentOptionsController(OemUnlockPreferenceController.class);
mDashboard.onOemUnlockDialogDismissed(); mDashboard.onOemUnlockDialogDismissed();
verify(controller).onOemUnlockDismissed(); verify(controller).onOemUnlockDismissed();
} }
@@ -202,7 +201,7 @@ public class DevelopmentSettingsDashboardFragmentTest {
public void onAdbDialogConfirmed_shouldCallControllerDialogConfirmed() { public void onAdbDialogConfirmed_shouldCallControllerDialogConfirmed() {
final AdbPreferenceController controller = mock(AdbPreferenceController.class); final AdbPreferenceController controller = mock(AdbPreferenceController.class);
doReturn(controller).when(mDashboard) doReturn(controller).when(mDashboard)
.getDevelopmentOptionsController(AdbPreferenceController.class); .getDevelopmentOptionsController(AdbPreferenceController.class);
mDashboard.onEnableAdbDialogConfirmed(); mDashboard.onEnableAdbDialogConfirmed();
verify(controller).onAdbDialogConfirmed(); verify(controller).onAdbDialogConfirmed();
@@ -212,7 +211,7 @@ public class DevelopmentSettingsDashboardFragmentTest {
public void onAdbDialogDismissed_shouldCallControllerOemDismissed() { public void onAdbDialogDismissed_shouldCallControllerOemDismissed() {
final AdbPreferenceController controller = mock(AdbPreferenceController.class); final AdbPreferenceController controller = mock(AdbPreferenceController.class);
doReturn(controller).when(mDashboard) doReturn(controller).when(mDashboard)
.getDevelopmentOptionsController(AdbPreferenceController.class); .getDevelopmentOptionsController(AdbPreferenceController.class);
mDashboard.onEnableAdbDialogDismissed(); mDashboard.onEnableAdbDialogDismissed();
verify(controller).onAdbDialogDismissed(); verify(controller).onAdbDialogDismissed();
@@ -221,9 +220,9 @@ public class DevelopmentSettingsDashboardFragmentTest {
@Test @Test
public void onAdbClearKeysDialogConfirmed_shouldCallControllerDialogConfirmed() { public void onAdbClearKeysDialogConfirmed_shouldCallControllerDialogConfirmed() {
final ClearAdbKeysPreferenceController controller = final ClearAdbKeysPreferenceController controller =
mock(ClearAdbKeysPreferenceController.class); mock(ClearAdbKeysPreferenceController.class);
doReturn(controller).when(mDashboard) doReturn(controller).when(mDashboard)
.getDevelopmentOptionsController(ClearAdbKeysPreferenceController.class); .getDevelopmentOptionsController(ClearAdbKeysPreferenceController.class);
mDashboard.onAdbClearKeysDialogConfirmed(); mDashboard.onAdbClearKeysDialogConfirmed();
verify(controller).onClearAdbKeysConfirmed(); verify(controller).onClearAdbKeysConfirmed();
@@ -232,9 +231,9 @@ public class DevelopmentSettingsDashboardFragmentTest {
@Test @Test
public void onDisableLogPersistDialogConfirmed_shouldCallControllerDialogConfirmed() { public void onDisableLogPersistDialogConfirmed_shouldCallControllerDialogConfirmed() {
final LogPersistPreferenceController controller = final LogPersistPreferenceController controller =
mock(LogPersistPreferenceController.class); mock(LogPersistPreferenceController.class);
doReturn(controller).when(mDashboard) doReturn(controller).when(mDashboard)
.getDevelopmentOptionsController(LogPersistPreferenceController.class); .getDevelopmentOptionsController(LogPersistPreferenceController.class);
mDashboard.onDisableLogPersistDialogConfirmed(); mDashboard.onDisableLogPersistDialogConfirmed();
verify(controller).onDisableLogPersistDialogConfirmed(); verify(controller).onDisableLogPersistDialogConfirmed();
@@ -243,9 +242,9 @@ public class DevelopmentSettingsDashboardFragmentTest {
@Test @Test
public void onDisableLogPersistDialogRejected_shouldCallControllerDialogRejected() { public void onDisableLogPersistDialogRejected_shouldCallControllerDialogRejected() {
final LogPersistPreferenceController controller = final LogPersistPreferenceController controller =
mock(LogPersistPreferenceController.class); mock(LogPersistPreferenceController.class);
doReturn(controller).when(mDashboard) doReturn(controller).when(mDashboard)
.getDevelopmentOptionsController(LogPersistPreferenceController.class); .getDevelopmentOptionsController(LogPersistPreferenceController.class);
mDashboard.onDisableLogPersistDialogRejected(); mDashboard.onDisableLogPersistDialogRejected();
verify(controller).onDisableLogPersistDialogRejected(); verify(controller).onDisableLogPersistDialogRejected();

View File

@@ -24,11 +24,11 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.content.Context; import android.content.Context;
import android.os.UserManager;
import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LifecycleOwner;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settings.testutils.shadow.ShadowUtils; import com.android.settings.testutils.shadow.ShadowUtils;
import com.android.settings.widget.SwitchBar; import com.android.settings.widget.SwitchBar;
import com.android.settings.widget.SwitchBar.OnSwitchChangeListener; import com.android.settings.widget.SwitchBar.OnSwitchChangeListener;
@@ -41,14 +41,13 @@ import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
import java.util.List; import java.util.List;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = ShadowUtils.class) @Config(shadows = {ShadowUtils.class, ShadowUserManager.class})
public class DevelopmentSwitchBarControllerTest { public class DevelopmentSwitchBarControllerTest {
@Mock @Mock
@@ -61,8 +60,7 @@ public class DevelopmentSwitchBarControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
final Context context = RuntimeEnvironment.application; final Context context = RuntimeEnvironment.application;
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); ShadowUserManager.getShadow().setIsAdminUser(true);
Shadows.shadowOf(userManager).setIsAdminUser(true);
mLifecycleOwner = () -> mLifecycle; mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner); mLifecycle = new Lifecycle(mLifecycleOwner);
mSwitchBar = new SwitchBar(context); mSwitchBar = new SwitchBar(context);
@@ -72,6 +70,7 @@ public class DevelopmentSwitchBarControllerTest {
@After @After
public void tearDown() { public void tearDown() {
ShadowUtils.reset(); ShadowUtils.reset();
ShadowUserManager.getShadow().reset();
} }
@Test @Test

View File

@@ -61,7 +61,7 @@ public class DisableAutomaticUpdatesPreferenceControllerTest {
public void onPreferenceChanged_turnOnAutomaticUpdates() { public void onPreferenceChanged_turnOnAutomaticUpdates() {
mController.onPreferenceChange(null, true); mController.onPreferenceChange(null, true);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, -1); Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, -1);
assertThat(mode).isEqualTo( assertThat(mode).isEqualTo(
@@ -72,7 +72,7 @@ public class DisableAutomaticUpdatesPreferenceControllerTest {
public void onPreferenceChanged_turnOffAutomaticUpdates() { public void onPreferenceChanged_turnOffAutomaticUpdates() {
mController.onPreferenceChange(null, false); mController.onPreferenceChange(null, false);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, -1); Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, -1);
assertThat(mode).isEqualTo( assertThat(mode).isEqualTo(
@@ -81,7 +81,7 @@ public class DisableAutomaticUpdatesPreferenceControllerTest {
@Test @Test
public void updateState_preferenceShouldBeChecked() { public void updateState_preferenceShouldBeChecked() {
Settings.System Settings.Global
.putInt(mContext.getContentResolver(), Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, .putInt(mContext.getContentResolver(), Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE,
DisableAutomaticUpdatesPreferenceController.ENABLE_UPDATES_SETTING); DisableAutomaticUpdatesPreferenceController.ENABLE_UPDATES_SETTING);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -91,7 +91,7 @@ public class DisableAutomaticUpdatesPreferenceControllerTest {
@Test @Test
public void updateState_preferenceShouldNotBeChecked() { public void updateState_preferenceShouldNotBeChecked() {
Settings.System Settings.Global
.putInt(mContext.getContentResolver(), Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, .putInt(mContext.getContentResolver(), Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE,
DisableAutomaticUpdatesPreferenceController.DISABLE_UPDATES_SETTING); DisableAutomaticUpdatesPreferenceController.DISABLE_UPDATES_SETTING);
mController.updateState(mPreference); mController.updateState(mPreference);

View File

@@ -84,7 +84,7 @@ public class KeepActivitiesPreferenceControllerTest {
@Test @Test
public void updateState_settingEnabled_preferenceShouldBeChecked() { public void updateState_settingEnabled_preferenceShouldBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.ALWAYS_FINISH_ACTIVITIES, SETTING_VALUE_ON); Settings.Global.ALWAYS_FINISH_ACTIVITIES, SETTING_VALUE_ON);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -93,7 +93,7 @@ public class KeepActivitiesPreferenceControllerTest {
@Test @Test
public void updateState_settingDisabled_preferenceShouldNotBeChecked() { public void updateState_settingDisabled_preferenceShouldNotBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.ALWAYS_FINISH_ACTIVITIES, SETTING_VALUE_OFF); Settings.Global.ALWAYS_FINISH_ACTIVITIES, SETTING_VALUE_OFF);
mController.updateState(mPreference); mController.updateState(mPreference);

View File

@@ -61,7 +61,7 @@ public class MobileDataAlwaysOnPreferenceControllerTest {
public void onPreferenceChanged_turnOnPreference_shouldEnableMobileDataAlwaysOn() { public void onPreferenceChanged_turnOnPreference_shouldEnableMobileDataAlwaysOn() {
mController.onPreferenceChange(mPreference, true /* new value */); mController.onPreferenceChange(mPreference, true /* new value */);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.MOBILE_DATA_ALWAYS_ON, -1 /* default */); Settings.Global.MOBILE_DATA_ALWAYS_ON, -1 /* default */);
assertThat(mode).isEqualTo(MobileDataAlwaysOnPreferenceController.SETTING_VALUE_ON); assertThat(mode).isEqualTo(MobileDataAlwaysOnPreferenceController.SETTING_VALUE_ON);
@@ -71,7 +71,7 @@ public class MobileDataAlwaysOnPreferenceControllerTest {
public void onPreferenceChanged_turnOffPreference_shouldDisableMobileDataAlwaysOn() { public void onPreferenceChanged_turnOffPreference_shouldDisableMobileDataAlwaysOn() {
mController.onPreferenceChange(mPreference, false /* new value */); mController.onPreferenceChange(mPreference, false /* new value */);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.MOBILE_DATA_ALWAYS_ON, -1 /* default */); Settings.Global.MOBILE_DATA_ALWAYS_ON, -1 /* default */);
assertThat(mode).isEqualTo(MobileDataAlwaysOnPreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(MobileDataAlwaysOnPreferenceController.SETTING_VALUE_OFF);
@@ -79,7 +79,7 @@ public class MobileDataAlwaysOnPreferenceControllerTest {
@Test @Test
public void updateState_settingEnabled_preferenceShouldBeChecked() { public void updateState_settingEnabled_preferenceShouldBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON,
MobileDataAlwaysOnPreferenceController.SETTING_VALUE_ON); MobileDataAlwaysOnPreferenceController.SETTING_VALUE_ON);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -88,7 +88,7 @@ public class MobileDataAlwaysOnPreferenceControllerTest {
@Test @Test
public void updateState_settingDisabled_preferenceShouldNotBeChecked() { public void updateState_settingDisabled_preferenceShouldNotBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON,
MobileDataAlwaysOnPreferenceController.SETTING_VALUE_OFF); MobileDataAlwaysOnPreferenceController.SETTING_VALUE_OFF);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -98,7 +98,7 @@ public class MobileDataAlwaysOnPreferenceControllerTest {
@Test @Test
public void onDeveloperOptionsSwitchDisabled_preferenceShouldBeDisabled() { public void onDeveloperOptionsSwitchDisabled_preferenceShouldBeDisabled() {
mController.onDeveloperOptionsSwitchDisabled(); mController.onDeveloperOptionsSwitchDisabled();
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.MOBILE_DATA_ALWAYS_ON, -1 /* default */); Settings.Global.MOBILE_DATA_ALWAYS_ON, -1 /* default */);
assertThat(mode).isEqualTo(MobileDataAlwaysOnPreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(MobileDataAlwaysOnPreferenceController.SETTING_VALUE_OFF);

View File

@@ -72,7 +72,7 @@ public class StayAwakePreferenceControllerTest {
public void onPreferenceChanged_turnOnStayAwake() { public void onPreferenceChanged_turnOnStayAwake() {
mController.onPreferenceChange(null, true); mController.onPreferenceChange(null, true);
final int mode = Settings.System.getInt(mContentResolver, final int mode = Settings.Global.getInt(mContentResolver,
Settings.Global.STAY_ON_WHILE_PLUGGED_IN, -1); Settings.Global.STAY_ON_WHILE_PLUGGED_IN, -1);
assertThat(mode).isEqualTo(StayAwakePreferenceController.SETTING_VALUE_ON); assertThat(mode).isEqualTo(StayAwakePreferenceController.SETTING_VALUE_ON);
@@ -82,7 +82,7 @@ public class StayAwakePreferenceControllerTest {
public void onPreferenceChanged_turnOffStayAwake() { public void onPreferenceChanged_turnOffStayAwake() {
mController.onPreferenceChange(null, false); mController.onPreferenceChange(null, false);
final int mode = Settings.System.getInt(mContentResolver, final int mode = Settings.Global.getInt(mContentResolver,
Settings.Global.STAY_ON_WHILE_PLUGGED_IN, -1); Settings.Global.STAY_ON_WHILE_PLUGGED_IN, -1);
assertThat(mode).isEqualTo(StayAwakePreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(StayAwakePreferenceController.SETTING_VALUE_OFF);
@@ -90,7 +90,7 @@ public class StayAwakePreferenceControllerTest {
@Test @Test
public void updateState_preferenceShouldBeChecked() { public void updateState_preferenceShouldBeChecked() {
Settings.System.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN, Settings.Global.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
StayAwakePreferenceController.SETTING_VALUE_ON); StayAwakePreferenceController.SETTING_VALUE_ON);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -99,7 +99,7 @@ public class StayAwakePreferenceControllerTest {
@Test @Test
public void updateState_preferenceShouldNotBeChecked() { public void updateState_preferenceShouldNotBeChecked() {
Settings.System.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN, Settings.Global.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
StayAwakePreferenceController.SETTING_VALUE_OFF); StayAwakePreferenceController.SETTING_VALUE_OFF);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -119,7 +119,7 @@ public class StayAwakePreferenceControllerTest {
@Test @Test
public void observerOnChangeCalledWithSameUri_preferenceShouldBeUpdated() { public void observerOnChangeCalledWithSameUri_preferenceShouldBeUpdated() {
Settings.System.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN, Settings.Global.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
StayAwakePreferenceController.SETTING_VALUE_ON); StayAwakePreferenceController.SETTING_VALUE_ON);
mController.onResume(); mController.onResume();
mController.mSettingsObserver.onChange(false, mController.mSettingsObserver.onChange(false,
@@ -130,7 +130,7 @@ public class StayAwakePreferenceControllerTest {
@Test @Test
public void observerOnChangeCalledWithDifferentUri_preferenceShouldNotBeUpdated() { public void observerOnChangeCalledWithDifferentUri_preferenceShouldNotBeUpdated() {
Settings.System.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN, Settings.Global.putInt(mContentResolver, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
StayAwakePreferenceController.SETTING_VALUE_ON); StayAwakePreferenceController.SETTING_VALUE_ON);
mController.onResume(); mController.onResume();
mController.mSettingsObserver.onChange(false, null); mController.mSettingsObserver.onChange(false, null);

View File

@@ -61,7 +61,7 @@ public class TetheringHardwareAccelPreferenceControllerTest {
public void onPreferenceChanged_settingEnabled_turnOnTetheringAccel() { public void onPreferenceChanged_settingEnabled_turnOnTetheringAccel() {
mController.onPreferenceChange(mPreference, true /* new value */); mController.onPreferenceChange(mPreference, true /* new value */);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.TETHER_OFFLOAD_DISABLED, -1 /* default */); Settings.Global.TETHER_OFFLOAD_DISABLED, -1 /* default */);
assertThat(mode).isEqualTo(TetheringHardwareAccelPreferenceController.SETTING_VALUE_ON); assertThat(mode).isEqualTo(TetheringHardwareAccelPreferenceController.SETTING_VALUE_ON);
@@ -71,7 +71,7 @@ public class TetheringHardwareAccelPreferenceControllerTest {
public void onPreferenceChanged_settingDisabled_turnOffTetheringAccel() { public void onPreferenceChanged_settingDisabled_turnOffTetheringAccel() {
mController.onPreferenceChange(mPreference, false /* new value */); mController.onPreferenceChange(mPreference, false /* new value */);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.TETHER_OFFLOAD_DISABLED, -1 /* default */); Settings.Global.TETHER_OFFLOAD_DISABLED, -1 /* default */);
assertThat(mode).isEqualTo(TetheringHardwareAccelPreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(TetheringHardwareAccelPreferenceController.SETTING_VALUE_OFF);
@@ -79,7 +79,7 @@ public class TetheringHardwareAccelPreferenceControllerTest {
@Test @Test
public void updateState_settingEnabled_preferenceShouldBeChecked() { public void updateState_settingEnabled_preferenceShouldBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.TETHER_OFFLOAD_DISABLED, Settings.Global.TETHER_OFFLOAD_DISABLED,
TetheringHardwareAccelPreferenceController.SETTING_VALUE_ON); TetheringHardwareAccelPreferenceController.SETTING_VALUE_ON);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -89,7 +89,7 @@ public class TetheringHardwareAccelPreferenceControllerTest {
@Test @Test
public void updateState_settingDisabled_preferenceShouldNotBeChecked() { public void updateState_settingDisabled_preferenceShouldNotBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.TETHER_OFFLOAD_DISABLED, Settings.Global.TETHER_OFFLOAD_DISABLED,
TetheringHardwareAccelPreferenceController.SETTING_VALUE_OFF); TetheringHardwareAccelPreferenceController.SETTING_VALUE_OFF);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -100,7 +100,7 @@ public class TetheringHardwareAccelPreferenceControllerTest {
@Test @Test
public void onDeveloperOptionsSwitchDisabled_shouldDisablePreference() { public void onDeveloperOptionsSwitchDisabled_shouldDisablePreference() {
mController.onDeveloperOptionsSwitchDisabled(); mController.onDeveloperOptionsSwitchDisabled();
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.TETHER_OFFLOAD_DISABLED, -1 /* default */); Settings.Global.TETHER_OFFLOAD_DISABLED, -1 /* default */);
assertThat(mode).isEqualTo(TetheringHardwareAccelPreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(TetheringHardwareAccelPreferenceController.SETTING_VALUE_OFF);

View File

@@ -61,7 +61,7 @@ public class WifiDisplayCertificationPreferenceControllerTest {
public void onPreferenceChanged_turnOnWifiDisplayCertification() { public void onPreferenceChanged_turnOnWifiDisplayCertification() {
mController.onPreferenceChange(mPreference, true /* new value */); mController.onPreferenceChange(mPreference, true /* new value */);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, -1 /* default */); Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, -1 /* default */);
assertThat(mode).isEqualTo(WifiDisplayCertificationPreferenceController.SETTING_VALUE_ON); assertThat(mode).isEqualTo(WifiDisplayCertificationPreferenceController.SETTING_VALUE_ON);
@@ -71,7 +71,7 @@ public class WifiDisplayCertificationPreferenceControllerTest {
public void onPreferenceChanged_turnOffWifiDisplayCertification() { public void onPreferenceChanged_turnOffWifiDisplayCertification() {
mController.onPreferenceChange(mPreference, false /* new value */); mController.onPreferenceChange(mPreference, false /* new value */);
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, -1 /* default */); Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, -1 /* default */);
assertThat(mode).isEqualTo(WifiDisplayCertificationPreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(WifiDisplayCertificationPreferenceController.SETTING_VALUE_OFF);
@@ -79,7 +79,7 @@ public class WifiDisplayCertificationPreferenceControllerTest {
@Test @Test
public void updateState_preferenceShouldBeChecked() { public void updateState_preferenceShouldBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON,
WifiDisplayCertificationPreferenceController.SETTING_VALUE_ON); WifiDisplayCertificationPreferenceController.SETTING_VALUE_ON);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -89,7 +89,7 @@ public class WifiDisplayCertificationPreferenceControllerTest {
@Test @Test
public void updateState_preferenceShouldNotBeChecked() { public void updateState_preferenceShouldNotBeChecked() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON,
WifiDisplayCertificationPreferenceController.SETTING_VALUE_OFF); WifiDisplayCertificationPreferenceController.SETTING_VALUE_OFF);
mController.updateState(mPreference); mController.updateState(mPreference);
@@ -100,7 +100,7 @@ public class WifiDisplayCertificationPreferenceControllerTest {
@Test @Test
public void onDeveloperOptionsDisabled_shouldDisablePreference() { public void onDeveloperOptionsDisabled_shouldDisablePreference() {
mController.onDeveloperOptionsDisabled(); mController.onDeveloperOptionsDisabled();
final int mode = Settings.System.getInt(mContext.getContentResolver(), final int mode = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, -1 /* default */); Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, -1 /* default */);
assertThat(mode).isEqualTo(WifiDisplayCertificationPreferenceController.SETTING_VALUE_OFF); assertThat(mode).isEqualTo(WifiDisplayCertificationPreferenceController.SETTING_VALUE_OFF);

View File

@@ -24,6 +24,7 @@ import static org.mockito.Mockito.verify;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.UserManager;
import android.service.quicksettings.Tile; import android.service.quicksettings.Tile;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
@@ -35,6 +36,9 @@ import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric; import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.shadows.ShadowUserManager;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class DevelopmentTilesTest { public class DevelopmentTilesTest {
@@ -50,6 +54,9 @@ public class DevelopmentTilesTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mService = spy(Robolectric.setupService(DevelopmentTiles.ShowLayout.class)); mService = spy(Robolectric.setupService(DevelopmentTiles.ShowLayout.class));
final ShadowUserManager um = Shadows.shadowOf(
RuntimeEnvironment.application.getSystemService(UserManager.class));
um.setIsAdminUser(true);
doReturn(mTile).when(mService).getQsTile(); doReturn(mTile).when(mService).getQsTile();
} }

View File

@@ -81,10 +81,8 @@ public class BuildNumberPreferenceControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application; mContext = RuntimeEnvironment.application;
final UserManager userManager = mShadowUserManager = Shadows.shadowOf(
(UserManager) mContext.getSystemService(Context.USER_SERVICE); RuntimeEnvironment.application.getSystemService(UserManager.class));
mShadowUserManager = Shadows.shadowOf(userManager);
mShadowUserManager.setIsAdminUser(true);
mFactory = FakeFeatureFactory.setupForTest(); mFactory = FakeFeatureFactory.setupForTest();
mLifecycleOwner = () -> mLifecycle; mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner); mLifecycle = new Lifecycle(mLifecycleOwner);
@@ -101,8 +99,6 @@ public class BuildNumberPreferenceControllerTest {
@After @After
public void tearDown() { public void tearDown() {
ShadowUtils.reset(); ShadowUtils.reset();
mShadowUserManager.setIsAdminUser(false);
mShadowUserManager.setIsDemoUser(false);
} }
@Test @Test
@@ -201,6 +197,7 @@ public class BuildNumberPreferenceControllerTest {
@Test @Test
public void onActivityResult_confirmPasswordRequestCompleted_enableDevPref() { public void onActivityResult_confirmPasswordRequestCompleted_enableDevPref() {
mShadowUserManager.setIsAdminUser(true);
mController = mController =
new BuildNumberPreferenceController(mContext, mActivity, mFragment, mLifecycle); new BuildNumberPreferenceController(mContext, mActivity, mFragment, mLifecycle);

View File

@@ -44,6 +44,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@@ -67,7 +68,7 @@ public class DeviceNamePreferenceControllerTest {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.WIFI_SERVICE, mWifiManager); shadowApplication.setSystemService(Context.WIFI_SERVICE, mWifiManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mPreference = new ValidatedEditTextPreference(mContext); mPreference = new ValidatedEditTextPreference(mContext);
when(mScreen.findPreference(anyString())).thenReturn(mPreference); when(mScreen.findPreference(anyString())).thenReturn(mPreference);
final WifiConfiguration configuration = new WifiConfiguration(); final WifiConfiguration configuration = new WifiConfiguration();

View File

@@ -22,6 +22,7 @@ import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.storage.VolumeInfo; import android.os.storage.VolumeInfo;
import android.view.Menu; import android.view.Menu;
@@ -37,7 +38,7 @@ import org.junit.runner.RunWith;
import org.mockito.Answers; import org.mockito.Answers;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -68,7 +69,7 @@ public class PrivateVolumeOptionMenuControllerTest {
when(mMigrateMenuItem.getItemId()).thenReturn(100); when(mMigrateMenuItem.getItemId()).thenReturn(100);
mController = new PrivateVolumeOptionMenuController( mController = new PrivateVolumeOptionMenuController(
RuntimeEnvironment.application, mPrimaryInfo, mPm); Robolectric.setupActivity(Activity.class), mPrimaryInfo, mPm);
} }
@Test @Test

View File

@@ -29,6 +29,7 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.Build; import android.os.Build;
@@ -41,7 +42,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
import java.util.Collections; import java.util.Collections;
@@ -62,7 +63,7 @@ public class SecurityPatchLevelDialogControllerTest {
@Before @Before
public void setup() { public void setup() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
when(mDialog.getContext()).thenReturn(mContext); when(mDialog.getContext()).thenReturn(mContext);
} }
@@ -91,7 +92,7 @@ public class SecurityPatchLevelDialogControllerTest {
@Test @Test
public void onClick_noActivityIntent_shouldDoNothing() { public void onClick_noActivityIntent_shouldDoNothing() {
when(mPackageManager.queryIntentActivities(any(), anyInt())) when(mPackageManager.queryIntentActivities(any(), anyInt()))
.thenReturn(Collections.emptyList()); .thenReturn(Collections.emptyList());
mController = new SecurityPatchLevelDialogController(mDialog); mController = new SecurityPatchLevelDialogController(mDialog);
ReflectionHelpers.setField(mController, "mPackageManager", mPackageManager); ReflectionHelpers.setField(mController, "mPackageManager", mPackageManager);
@@ -103,7 +104,7 @@ public class SecurityPatchLevelDialogControllerTest {
@Test @Test
public void onClick_activityIntentFound_shouldStartActivity() { public void onClick_activityIntentFound_shouldStartActivity() {
when(mPackageManager.queryIntentActivities(any(), anyInt())) when(mPackageManager.queryIntentActivities(any(), anyInt()))
.thenReturn(Collections.singletonList(null)); .thenReturn(Collections.singletonList(null));
mController = new SecurityPatchLevelDialogController(mDialog); mController = new SecurityPatchLevelDialogController(mDialog);
ReflectionHelpers.setField(mController, "mPackageManager", mPackageManager); ReflectionHelpers.setField(mController, "mPackageManager", mPackageManager);

View File

@@ -28,6 +28,7 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.os.storage.VolumeInfo; import android.os.storage.VolumeInfo;
import android.text.format.Formatter; import android.text.format.Formatter;
@@ -51,15 +52,15 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import java.io.File; import java.io.File;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = { @Config(shadows = {
SettingsShadowResources.class, SettingsShadowResources.class,
SettingsShadowResources.SettingsShadowTheme.class SettingsShadowResources.SettingsShadowTheme.class
}) })
public class StorageSummaryDonutPreferenceControllerTest { public class StorageSummaryDonutPreferenceControllerTest {
@@ -74,7 +75,7 @@ public class StorageSummaryDonutPreferenceControllerTest {
public void setUp() throws Exception { public void setUp() throws Exception {
SettingsShadowResources.overrideResource( SettingsShadowResources.overrideResource(
com.android.internal.R.string.config_headlineFontFamily, ""); com.android.internal.R.string.config_headlineFontFamily, "");
mContext = spy(RuntimeEnvironment.application.getApplicationContext()); mContext = spy(Robolectric.setupActivity(Activity.class));
mFakeFeatureFactory = FakeFeatureFactory.setupForTest(); mFakeFeatureFactory = FakeFeatureFactory.setupForTest();
mMetricsFeatureProvider = mFakeFeatureFactory.getMetricsFeatureProvider(); mMetricsFeatureProvider = mFakeFeatureFactory.getMetricsFeatureProvider();
mController = new StorageSummaryDonutPreferenceController(mContext); mController = new StorageSummaryDonutPreferenceController(mContext);
@@ -82,7 +83,8 @@ public class StorageSummaryDonutPreferenceControllerTest {
LayoutInflater inflater = LayoutInflater.from(mContext); LayoutInflater inflater = LayoutInflater.from(mContext);
final View view = final View view =
inflater.inflate(mPreference.getLayoutResource(), new LinearLayout(mContext), false); inflater.inflate(mPreference.getLayoutResource(), new LinearLayout(mContext),
false);
mHolder = PreferenceViewHolder.createInstanceForTests(view); mHolder = PreferenceViewHolder.createInstanceForTests(view);
} }
@@ -92,37 +94,37 @@ public class StorageSummaryDonutPreferenceControllerTest {
} }
@Test @Test
public void testEmpty() throws Exception { public void testEmpty() {
final long totalSpace = 32 * GIGABYTE; final long totalSpace = 32 * GIGABYTE;
final long usedSpace = 0; final long usedSpace = 0;
mController.updateBytes(0, 32 * GIGABYTE); mController.updateBytes(0, 32 * GIGABYTE);
mController.updateState(mPreference); mController.updateState(mPreference);
final Formatter.BytesResult usedSpaceResults = final Formatter.BytesResult usedSpaceResults =
Formatter.formatBytes(mContext.getResources(), usedSpace, 0 /* flags */); Formatter.formatBytes(mContext.getResources(), usedSpace, 0 /* flags */);
assertThat(mPreference.getTitle().toString()) assertThat(mPreference.getTitle().toString())
.isEqualTo(usedSpaceResults.value + " " + usedSpaceResults.units); .isEqualTo(usedSpaceResults.value + " " + usedSpaceResults.units);
assertThat(mPreference.getSummary().toString()) assertThat(mPreference.getSummary().toString())
.isEqualTo("Used of " + Formatter.formatShortFileSize(mContext, totalSpace)); .isEqualTo("Used of " + Formatter.formatShortFileSize(mContext, totalSpace));
} }
@Test @Test
public void testTotalStorage() throws Exception { public void testTotalStorage() {
final long totalSpace = KILOBYTE * 10; final long totalSpace = KILOBYTE * 10;
final long usedSpace = KILOBYTE; final long usedSpace = KILOBYTE;
mController.updateBytes(KILOBYTE, totalSpace); mController.updateBytes(KILOBYTE, totalSpace);
mController.updateState(mPreference); mController.updateState(mPreference);
final Formatter.BytesResult usedSpaceResults = final Formatter.BytesResult usedSpaceResults =
Formatter.formatBytes(mContext.getResources(), usedSpace, 0 /* flags */); Formatter.formatBytes(mContext.getResources(), usedSpace, 0 /* flags */);
assertThat(mPreference.getTitle().toString()) assertThat(mPreference.getTitle().toString())
.isEqualTo(usedSpaceResults.value + " " + usedSpaceResults.units); .isEqualTo(usedSpaceResults.value + " " + usedSpaceResults.units);
assertThat(mPreference.getSummary().toString()) assertThat(mPreference.getSummary().toString())
.isEqualTo("Used of " + Formatter.formatShortFileSize(mContext, totalSpace)); .isEqualTo("Used of " + Formatter.formatShortFileSize(mContext, totalSpace));
} }
@Test @Test
public void testPopulateWithVolume() throws Exception { public void testPopulateWithVolume() {
final long totalSpace = KILOBYTE * 10; final long totalSpace = KILOBYTE * 10;
final long freeSpace = KILOBYTE; final long freeSpace = KILOBYTE;
final long usedSpace = totalSpace - freeSpace; final long usedSpace = totalSpace - freeSpace;
@@ -138,21 +140,21 @@ public class StorageSummaryDonutPreferenceControllerTest {
mController.updateState(mPreference); mController.updateState(mPreference);
final Formatter.BytesResult usedSpaceResults = final Formatter.BytesResult usedSpaceResults =
Formatter.formatBytes(mContext.getResources(), usedSpace, 0 /* flags */); Formatter.formatBytes(mContext.getResources(), usedSpace, 0 /* flags */);
assertThat(mPreference.getTitle().toString()) assertThat(mPreference.getTitle().toString())
.isEqualTo(usedSpaceResults.value + " " + usedSpaceResults.units); .isEqualTo(usedSpaceResults.value + " " + usedSpaceResults.units);
assertThat(mPreference.getSummary().toString()) assertThat(mPreference.getSummary().toString())
.isEqualTo("Used of " + Formatter.formatShortFileSize(mContext, totalSpace)); .isEqualTo("Used of " + Formatter.formatShortFileSize(mContext, totalSpace));
} }
@Test @Test
public void testFreeUpSpaceMetricIsTriggered() throws Exception { public void testFreeUpSpaceMetricIsTriggered() {
mPreference.onBindViewHolder(mHolder); mPreference.onBindViewHolder(mHolder);
final Button button = (Button) mHolder.findViewById(R.id.deletion_helper_button); final Button button = (Button) mHolder.findViewById(R.id.deletion_helper_button);
mPreference.onClick(button); mPreference.onClick(button);
verify(mMetricsFeatureProvider, times(1)) verify(mMetricsFeatureProvider, times(1))
.action(any(Context.class), eq(MetricsEvent.STORAGE_FREE_UP_SPACE_NOW)); .action(any(Context.class), eq(MetricsEvent.STORAGE_FREE_UP_SPACE_NOW));
} }
} }

View File

@@ -25,6 +25,7 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.UserInfo; import android.content.pm.UserInfo;
@@ -47,7 +48,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class UserProfileControllerTest { public class UserProfileControllerTest {
@@ -64,7 +65,7 @@ public class UserProfileControllerTest {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
mPrimaryProfile = new UserInfo(); mPrimaryProfile = new UserInfo();
mController = new UserProfileController(mContext, mPrimaryProfile, 0); mController = new UserProfileController(mContext, mPrimaryProfile, 0);
when(mScreen.getContext()).thenReturn(mContext); when(mScreen.getContext()).thenReturn(mContext);
@@ -74,7 +75,7 @@ public class UserProfileControllerTest {
} }
@Test @Test
public void controllerAddsPrimaryProfilePreference() throws Exception { public void controllerAddsPrimaryProfilePreference() {
final ArgumentCaptor<Preference> argumentCaptor = ArgumentCaptor.forClass(Preference.class); final ArgumentCaptor<Preference> argumentCaptor = ArgumentCaptor.forClass(Preference.class);
verify(mScreen).addPreference(argumentCaptor.capture()); verify(mScreen).addPreference(argumentCaptor.capture());
final Preference preference = argumentCaptor.getValue(); final Preference preference = argumentCaptor.getValue();
@@ -84,7 +85,7 @@ public class UserProfileControllerTest {
} }
@Test @Test
public void tappingProfilePreferenceSendsToStorageProfileFragment() throws Exception { public void tappingProfilePreferenceSendsToStorageProfileFragment() {
final ArgumentCaptor<Preference> argumentCaptor = ArgumentCaptor.forClass(Preference.class); final ArgumentCaptor<Preference> argumentCaptor = ArgumentCaptor.forClass(Preference.class);
verify(mScreen).addPreference(argumentCaptor.capture()); verify(mScreen).addPreference(argumentCaptor.capture());
@@ -100,7 +101,7 @@ public class UserProfileControllerTest {
} }
@Test @Test
public void acceptingResultUpdatesPreferenceSize() throws Exception { public void acceptingResultUpdatesPreferenceSize() {
final SparseArray<StorageAsyncLoader.AppsStorageResult> result = new SparseArray<>(); final SparseArray<StorageAsyncLoader.AppsStorageResult> result = new SparseArray<>();
final StorageAsyncLoader.AppsStorageResult userResult = final StorageAsyncLoader.AppsStorageResult userResult =
new StorageAsyncLoader.AppsStorageResult(); new StorageAsyncLoader.AppsStorageResult();
@@ -121,7 +122,7 @@ public class UserProfileControllerTest {
} }
@Test @Test
public void iconCallbackChangesPreferenceIcon() throws Exception { public void iconCallbackChangesPreferenceIcon() {
final SparseArray<Drawable> icons = new SparseArray<>(); final SparseArray<Drawable> icons = new SparseArray<>();
final UserIconDrawable drawable = mock(UserIconDrawable.class); final UserIconDrawable drawable = mock(UserIconDrawable.class);
when(drawable.mutate()).thenReturn(drawable); when(drawable.mutate()).thenReturn(drawable);

View File

@@ -67,7 +67,7 @@ public class ActionDisabledByAdminDialogHelperTest {
@Before @Before
public void setUp() { public void setUp() {
mActivity = Robolectric.buildActivity(CustomActivity.class).get(); mActivity = Robolectric.setupActivity(CustomActivity.class);
mActivityShadow = Shadow.extract(mActivity); mActivityShadow = Shadow.extract(mActivity);
mHelper = new ActionDisabledByAdminDialogHelper(mActivity); mHelper = new ActionDisabledByAdminDialogHelper(mActivity);
} }

View File

@@ -26,6 +26,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import android.app.Activity;
import android.app.AppOpsManager; import android.app.AppOpsManager;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@@ -45,7 +46,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -92,7 +93,7 @@ public class RestrictAppPreferenceControllerTest {
mOtherUserPackageOps = new AppOpsManager.PackageOps( mOtherUserPackageOps = new AppOpsManager.PackageOps(
RESTRICTED_PACKAGE_NAME, OTHER_USER_UID, restrictedOps); RESTRICTED_PACKAGE_NAME, OTHER_USER_UID, restrictedOps);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
doReturn(mAppOpsManager).when(mContext).getSystemService(Context.APP_OPS_SERVICE); doReturn(mAppOpsManager).when(mContext).getSystemService(Context.APP_OPS_SERVICE);
doReturn(mUserManager).when(mContext).getSystemService(UserManager.class); doReturn(mUserManager).when(mContext).getSystemService(UserManager.class);
doReturn(mContext).when(mFragment).getContext(); doReturn(mContext).when(mFragment).getContext();

View File

@@ -18,6 +18,7 @@ package com.android.settings.fuelgauge.batterytip.actions;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import com.android.internal.logging.nano.MetricsProto; import com.android.internal.logging.nano.MetricsProto;
@@ -37,7 +38,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -63,7 +64,7 @@ public class OpenRestrictAppFragmentActionTest {
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application; mContext = Robolectric.setupActivity(Activity.class);
mAppInfos = new ArrayList<>(); mAppInfos = new ArrayList<>();
mAppInfos.add(new AppInfo.Builder() mAppInfos.add(new AppInfo.Builder()

View File

@@ -27,6 +27,7 @@ import androidx.preference.Preference;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider; import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.testutils.DrawableTestHelper;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -59,7 +60,7 @@ public class BatteryTipTest {
assertThat(preference.getTitle()).isEqualTo(TITLE); assertThat(preference.getTitle()).isEqualTo(TITLE);
assertThat(preference.getSummary()).isEqualTo(SUMMARY); assertThat(preference.getSummary()).isEqualTo(SUMMARY);
assertThat(preference.getIcon()).isEqualTo(mContext.getDrawable(ICON_ID)); DrawableTestHelper.assertDrawableResId(preference.getIcon(), ICON_ID);
} }
@Test @Test

View File

@@ -82,7 +82,7 @@ public class DoubleTapPowerPreferenceControllerTest {
@Test @Test
public void testIsChecked_configIsNotSet_shouldReturnTrue() { public void testIsChecked_configIsNotSet_shouldReturnTrue() {
// Set the setting to be enabled. // Set the setting to be enabled.
Settings.System.putInt(mContentResolver, CAMERA_DOUBLE_TAP_POWER_GESTURE_DISABLED, ON); Settings.Secure.putInt(mContentResolver, CAMERA_DOUBLE_TAP_POWER_GESTURE_DISABLED, ON);
mController = new DoubleTapPowerPreferenceController(mContext, KEY_DOUBLE_TAP_POWER); mController = new DoubleTapPowerPreferenceController(mContext, KEY_DOUBLE_TAP_POWER);
assertThat(mController.isChecked()).isTrue(); assertThat(mController.isChecked()).isTrue();
@@ -91,7 +91,7 @@ public class DoubleTapPowerPreferenceControllerTest {
@Test @Test
public void testIsChecked_configIsSet_shouldReturnFalse() { public void testIsChecked_configIsSet_shouldReturnFalse() {
// Set the setting to be disabled. // Set the setting to be disabled.
Settings.System.putInt(mContentResolver, CAMERA_DOUBLE_TAP_POWER_GESTURE_DISABLED, OFF); Settings.Secure.putInt(mContentResolver, CAMERA_DOUBLE_TAP_POWER_GESTURE_DISABLED, OFF);
mController = new DoubleTapPowerPreferenceController(mContext, KEY_DOUBLE_TAP_POWER); mController = new DoubleTapPowerPreferenceController(mContext, KEY_DOUBLE_TAP_POWER);
assertThat(mController.isChecked()).isFalse(); assertThat(mController.isChecked()).isFalse();

View File

@@ -139,7 +139,7 @@ public class DoubleTwistPreferenceControllerTest {
public void testIsChecked_configIsSet_shouldReturnTrue() { public void testIsChecked_configIsSet_shouldReturnTrue() {
// Set the setting to be enabled. // Set the setting to be enabled.
final Context context = RuntimeEnvironment.application; final Context context = RuntimeEnvironment.application;
Settings.System.putInt(context.getContentResolver(), Settings.Secure.putInt(context.getContentResolver(),
Settings.Secure.CAMERA_DOUBLE_TWIST_TO_FLIP_ENABLED, 1); Settings.Secure.CAMERA_DOUBLE_TWIST_TO_FLIP_ENABLED, 1);
mController = new DoubleTwistPreferenceController(context, KEY_DOUBLE_TWIST); mController = new DoubleTwistPreferenceController(context, KEY_DOUBLE_TWIST);
@@ -150,7 +150,7 @@ public class DoubleTwistPreferenceControllerTest {
public void testIsChecked_configIsNotSet_shouldReturnFalse() { public void testIsChecked_configIsNotSet_shouldReturnFalse() {
// Set the setting to be disabled. // Set the setting to be disabled.
final Context context = RuntimeEnvironment.application; final Context context = RuntimeEnvironment.application;
Settings.System.putInt(context.getContentResolver(), Settings.Secure.putInt(context.getContentResolver(),
Settings.Secure.CAMERA_DOUBLE_TWIST_TO_FLIP_ENABLED, 0); Settings.Secure.CAMERA_DOUBLE_TWIST_TO_FLIP_ENABLED, 0);
mController = new DoubleTwistPreferenceController(context, KEY_DOUBLE_TWIST); mController = new DoubleTwistPreferenceController(context, KEY_DOUBLE_TWIST);

View File

@@ -100,7 +100,7 @@ public class SwipeToNotificationPreferenceControllerTest {
when(mFingerprintManager.isHardwareDetected()).thenReturn(true); when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
// Set the setting to be enabled. // Set the setting to be enabled.
final Context context = RuntimeEnvironment.application; final Context context = RuntimeEnvironment.application;
Settings.System.putInt(context.getContentResolver(), SYSTEM_NAVIGATION_KEYS_ENABLED, 1); Settings.Secure.putInt(context.getContentResolver(), SYSTEM_NAVIGATION_KEYS_ENABLED, 1);
mController = new SwipeToNotificationPreferenceController(context, KEY_SWIPE_DOWN); mController = new SwipeToNotificationPreferenceController(context, KEY_SWIPE_DOWN);
assertThat(mController.isChecked()).isTrue(); assertThat(mController.isChecked()).isTrue();
@@ -112,7 +112,7 @@ public class SwipeToNotificationPreferenceControllerTest {
when(mFingerprintManager.isHardwareDetected()).thenReturn(true); when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
// Set the setting to be disabled. // Set the setting to be disabled.
final Context context = RuntimeEnvironment.application; final Context context = RuntimeEnvironment.application;
Settings.System.putInt(context.getContentResolver(), SYSTEM_NAVIGATION_KEYS_ENABLED, 0); Settings.Secure.putInt(context.getContentResolver(), SYSTEM_NAVIGATION_KEYS_ENABLED, 0);
mController = new SwipeToNotificationPreferenceController(context, KEY_SWIPE_DOWN); mController = new SwipeToNotificationPreferenceController(context, KEY_SWIPE_DOWN);
assertThat(mController.isChecked()).isFalse(); assertThat(mController.isChecked()).isFalse();

View File

@@ -21,7 +21,9 @@ import static com.google.common.truth.Truth.assertThat;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo; import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import com.android.internal.R; import com.android.internal.R;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
@@ -69,7 +71,14 @@ public class SwipeUpPreferenceControllerTest {
mContext.getString(com.android.internal.R.string.config_recentsComponentName)); mContext.getString(com.android.internal.R.string.config_recentsComponentName));
final Intent quickStepIntent = new Intent(ACTION_QUICKSTEP) final Intent quickStepIntent = new Intent(ACTION_QUICKSTEP)
.setPackage(recentsComponentName.getPackageName()); .setPackage(recentsComponentName.getPackageName());
mPackageManager.addResolveInfoForIntent(quickStepIntent, new ResolveInfo()); final ResolveInfo info = new ResolveInfo();
info.serviceInfo = new ServiceInfo();
info.resolvePackageName = recentsComponentName.getPackageName();
info.serviceInfo.packageName = info.resolvePackageName;
info.serviceInfo.name = recentsComponentName.getClassName();
info.serviceInfo.applicationInfo = new ApplicationInfo();
info.serviceInfo.applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
mPackageManager.addResolveInfoForIntent(quickStepIntent, info);
assertThat(SwipeUpPreferenceController.isGestureAvailable(mContext)).isTrue(); assertThat(SwipeUpPreferenceController.isGestureAvailable(mContext)).isTrue();
} }
@@ -121,7 +130,7 @@ public class SwipeUpPreferenceControllerTest {
@Test @Test
public void isSliceableCorrectKey_returnsTrue() { public void isSliceableCorrectKey_returnsTrue() {
final SwipeUpPreferenceController controller = final SwipeUpPreferenceController controller =
new SwipeUpPreferenceController(mContext,"gesture_swipe_up"); new SwipeUpPreferenceController(mContext, "gesture_swipe_up");
assertThat(controller.isSliceable()).isTrue(); assertThat(controller.isSliceable()).isTrue();
} }

View File

@@ -17,11 +17,11 @@ package com.android.settings.homepage.contextualcards.conditional;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.net.NetworkPolicyManager; import android.net.NetworkPolicyManager;
import com.android.settings.Settings; import com.android.settings.Settings;
@@ -30,10 +30,11 @@ import com.android.settings.testutils.SettingsRobolectricTestRunner;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowActivity;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -43,7 +44,7 @@ public class BackgroundDataConditionControllerTest {
private ConditionManager mConditionManager; private ConditionManager mConditionManager;
@Mock @Mock
private NetworkPolicyManager mNetworkPolicyManager; private NetworkPolicyManager mNetworkPolicyManager;
private Context mContext; private Activity mActivity;
private BackgroundDataConditionController mController; private BackgroundDataConditionController mController;
@Before @Before
@@ -51,19 +52,19 @@ public class BackgroundDataConditionControllerTest {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
ShadowApplication.getInstance().setSystemService(Context.NETWORK_POLICY_SERVICE, ShadowApplication.getInstance().setSystemService(Context.NETWORK_POLICY_SERVICE,
mNetworkPolicyManager); mNetworkPolicyManager);
mContext = spy(RuntimeEnvironment.application); mActivity = Robolectric.setupActivity(Activity.class);
mController = new BackgroundDataConditionController(mContext, mConditionManager); mController = new BackgroundDataConditionController(mActivity, mConditionManager);
} }
@Test @Test
public void onPrimaryClick_shouldReturn2SummaryActivity() { public void onPrimaryClick_shouldReturn2SummaryActivity() {
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class); final ComponentName componentName =
mController.onPrimaryClick(mContext); new ComponentName(mActivity, Settings.DataUsageSummaryActivity.class);
verify(mContext).startActivity(argumentCaptor.capture());
Intent intent = argumentCaptor.getValue();
assertThat(intent.getComponent().getClassName()).isEqualTo( mController.onPrimaryClick(mActivity);
Settings.DataUsageSummaryActivity.class.getName());
final ShadowActivity shadowActivity = Shadow.extract(mActivity);
assertThat(shadowActivity.getNextStartedActivity().getComponent()).isEqualTo(componentName);
} }
@Test @Test

View File

@@ -16,12 +16,12 @@
package com.android.settings.homepage.contextualcards.conditional; package com.android.settings.homepage.contextualcards.conditional;
import static org.mockito.ArgumentMatchers.argThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.spy;
import android.app.Activity;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Context;
import com.android.settings.Settings; import com.android.settings.Settings;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
@@ -31,32 +31,34 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowActivity;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class WorkModeConditionControllerTest { public class WorkModeConditionControllerTest {
@Mock @Mock
private ConditionManager mConditionManager; private ConditionManager mConditionManager;
private Context mContext; private Activity mActivity;
private WorkModeConditionController mController; private WorkModeConditionController mController;
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mActivity = spy(Robolectric.setupActivity(Activity.class));
mController = new WorkModeConditionController(mContext, mConditionManager); mController = new WorkModeConditionController(mActivity, mConditionManager);
} }
@Test @Test
public void onPrimaryClick_shouldLaunchAccountsSetting() { public void onPrimaryClick_shouldLaunchAccountsSetting() {
final ComponentName componentName = final ComponentName componentName =
new ComponentName(mContext, Settings.AccountDashboardActivity.class); new ComponentName(mActivity, Settings.AccountDashboardActivity.class);
mController.onPrimaryClick(mContext); mController.onPrimaryClick(mActivity);
verify(mContext).startActivity( final ShadowActivity shadowActivity = Shadow.extract(mActivity);
argThat(intent -> intent.getComponent().equals(componentName))); assertThat(shadowActivity.getNextStartedActivity().getComponent()).isEqualTo(componentName);
} }
} }

View File

@@ -31,16 +31,16 @@ public class AppLocationPermissionPreferenceControllerTest {
@Test @Test
public void isAvailable_noLocationLinkPermission_shouldReturnFalse() { public void isAvailable_noLocationLinkPermission_shouldReturnFalse() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.putInt(mContext.getContentResolver(),
android.provider.Settings.Global.LOCATION_SETTINGS_LINK_TO_PERMISSIONS_ENABLED, 0); Settings.Global.LOCATION_SETTINGS_LINK_TO_PERMISSIONS_ENABLED, 0);
assertThat(mController.isAvailable()).isFalse(); assertThat(mController.isAvailable()).isFalse();
} }
@Test @Test
public void displayPreference_hasLocationLinkPermission_shouldReturnTrue() { public void displayPreference_hasLocationLinkPermission_shouldReturnTrue() {
Settings.System.putInt(mContext.getContentResolver(), Settings.Global.putInt(mContext.getContentResolver(),
android.provider.Settings.Global.LOCATION_SETTINGS_LINK_TO_PERMISSIONS_ENABLED, 1); Settings.Global.LOCATION_SETTINGS_LINK_TO_PERMISSIONS_ENABLED, 1);
assertThat(mController.isAvailable()).isTrue(); assertThat(mController.isAvailable()).isTrue();
} }

View File

@@ -30,6 +30,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.robolectric.shadow.api.Shadow.extract; import static org.robolectric.shadow.api.Shadow.extract;
import android.app.Activity;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@@ -59,7 +60,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -83,7 +84,7 @@ public class MobileNetworkPreferenceControllerTest {
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
mLifecycleOwner = () -> mLifecycle; mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner); mLifecycle = new Lifecycle(mLifecycleOwner);
when(mContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager); when(mContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager);

View File

@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.content.Context; import android.content.Context;
import android.os.UserManager;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.ShadowRestrictedLockUtilsInternal; import com.android.settings.testutils.shadow.ShadowRestrictedLockUtilsInternal;
@@ -32,9 +33,12 @@ import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowUserManager;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = ShadowRestrictedLockUtilsInternal.class) @Config(shadows = ShadowRestrictedLockUtilsInternal.class)
public class TopLevelNetworkEntryPreferenceControllerTest { public class TopLevelNetworkEntryPreferenceControllerTest {
@@ -53,6 +57,10 @@ public class TopLevelNetworkEntryPreferenceControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application; mContext = RuntimeEnvironment.application;
final ShadowUserManager um = Shadows.shadowOf(
RuntimeEnvironment.application.getSystemService(UserManager.class));
um.setIsAdminUser(true);
mController = new TopLevelNetworkEntryPreferenceController(mContext, "test_key"); mController = new TopLevelNetworkEntryPreferenceController(mContext, "test_key");
ReflectionHelpers.setField(mController, "mWifiPreferenceController", ReflectionHelpers.setField(mController, "mWifiPreferenceController",
@@ -61,7 +69,6 @@ public class TopLevelNetworkEntryPreferenceControllerTest {
mMobileNetworkPreferenceController); mMobileNetworkPreferenceController);
ReflectionHelpers.setField(mController, "mTetherPreferenceController", ReflectionHelpers.setField(mController, "mTetherPreferenceController",
mTetherPreferenceController); mTetherPreferenceController);
} }
@Test @Test

View File

@@ -25,6 +25,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.PersistableBundle; import android.os.PersistableBundle;
@@ -44,7 +45,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class ApnPreferenceControllerTest { public class ApnPreferenceControllerTest {
@@ -67,7 +68,7 @@ public class ApnPreferenceControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
doReturn(mTelephonyManager).when(mContext).getSystemService(Context.TELEPHONY_SERVICE); doReturn(mTelephonyManager).when(mContext).getSystemService(Context.TELEPHONY_SERVICE);
doReturn(mSubscriptionManager).when(mContext).getSystemService(SubscriptionManager.class); doReturn(mSubscriptionManager).when(mContext).getSystemService(SubscriptionManager.class);
doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID); doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID);

View File

@@ -25,6 +25,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.net.Uri; import android.net.Uri;
@@ -47,7 +48,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class DataServiceSetupPreferenceControllerTest { public class DataServiceSetupPreferenceControllerTest {
@@ -71,7 +72,7 @@ public class DataServiceSetupPreferenceControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
doReturn(mTelephonyManager).when(mContext).getSystemService(Context.TELEPHONY_SERVICE); doReturn(mTelephonyManager).when(mContext).getSystemService(Context.TELEPHONY_SERVICE);
doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID); doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID);
doReturn(mInvalidTelephonyManager).when(mTelephonyManager).createForSubscriptionId( doReturn(mInvalidTelephonyManager).when(mTelephonyManager).createForSubscriptionId(

View File

@@ -22,6 +22,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.provider.Settings; import android.provider.Settings;
@@ -39,7 +40,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class DataUsagePreferenceControllerTest { public class DataUsagePreferenceControllerTest {
@@ -55,7 +56,7 @@ public class DataUsagePreferenceControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
doReturn(mTelephonyManager).when(mContext).getSystemService(Context.TELEPHONY_SERVICE); doReturn(mTelephonyManager).when(mContext).getSystemService(Context.TELEPHONY_SERVICE);
doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID); doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID);

View File

@@ -22,6 +22,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
@@ -37,7 +38,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment; import org.robolectric.Robolectric;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class EuiccPreferenceControllerTest { public class EuiccPreferenceControllerTest {
@@ -54,7 +55,7 @@ public class EuiccPreferenceControllerTest {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); mContext = spy(Robolectric.setupActivity(Activity.class));
doReturn(mTelephonyManager).when(mContext).getSystemService(Context.TELEPHONY_SERVICE); doReturn(mTelephonyManager).when(mContext).getSystemService(Context.TELEPHONY_SERVICE);
doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID); doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID);

View File

@@ -34,7 +34,6 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -48,10 +47,10 @@ public class NfcAirplaneModeObserverTest {
@Before @Before
public void setUp() { public void setUp() {
mContext = ShadowApplication.getInstance().getApplicationContext(); mContext = RuntimeEnvironment.application;
mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext); mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext);
mNfcPreference = new SwitchPreference(RuntimeEnvironment.application); mNfcPreference = new SwitchPreference(mContext);
mNfcAirplaneModeObserver = mNfcAirplaneModeObserver =
new NfcAirplaneModeObserver(mContext, mNfcAdapter, mNfcPreference); new NfcAirplaneModeObserver(mContext, mNfcAdapter, mNfcPreference);
@@ -76,7 +75,7 @@ public class NfcAirplaneModeObserverTest {
final ContentResolver contentResolver = mContext.getContentResolver(); final ContentResolver contentResolver = mContext.getContentResolver();
Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1); Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
Settings.Global.putString(contentResolver, Settings.Global.putString(contentResolver,
Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC); Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI); mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
@@ -89,7 +88,7 @@ public class NfcAirplaneModeObserverTest {
final ContentResolver contentResolver = mContext.getContentResolver(); final ContentResolver contentResolver = mContext.getContentResolver();
Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1); Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
Settings.Global.putString(contentResolver, Settings.Global.putString(contentResolver,
Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Global.RADIO_WIFI); Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Global.RADIO_WIFI);
mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI); mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);

View File

@@ -54,6 +54,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -81,7 +82,7 @@ public class BlockPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm);
shadowApplication.setSystemService(Context.USER_SERVICE, mUm); shadowApplication.setSystemService(Context.USER_SERVICE, mUm);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mController = spy(new BlockPreferenceController(mContext, mImportanceListener, mBackend)); mController = spy(new BlockPreferenceController(mContext, mImportanceListener, mBackend));
mSwitch = new SwitchBar(mContext); mSwitch = new SwitchBar(mContext);
when(mPreference.findViewById(R.id.switch_bar)).thenReturn(mSwitch); when(mPreference.findViewById(R.id.switch_bar)).thenReturn(mSwitch);

View File

@@ -27,6 +27,7 @@ import android.os.SystemProperties;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import androidx.preference.SwitchPreference; import androidx.preference.SwitchPreference;
import com.android.settings.R;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import org.junit.Before; import org.junit.Before;
@@ -35,7 +36,6 @@ import org.junit.runner.RunWith;
import org.mockito.Answers; import org.mockito.Answers;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.shadows.ShadowSystemProperties;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
public class BootSoundPreferenceControllerTest { public class BootSoundPreferenceControllerTest {
@@ -52,8 +52,8 @@ public class BootSoundPreferenceControllerTest {
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
when(mContext.getResources().getBoolean(com.android.settings.R.bool.has_boot_sounds)) when(mContext.getResources().getBoolean(R.bool.has_boot_sounds))
.thenReturn(true); .thenReturn(true);
mController = new BootSoundPreferenceController(mContext); mController = new BootSoundPreferenceController(mContext);
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference); when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
when(mPreference.getKey()).thenReturn(mController.getPreferenceKey()); when(mPreference.getKey()).thenReturn(mController.getPreferenceKey());
@@ -62,7 +62,7 @@ public class BootSoundPreferenceControllerTest {
@Test @Test
public void isAvailable_hasBootSounds_shouldReturnTrue() { public void isAvailable_hasBootSounds_shouldReturnTrue() {
when(mContext.getResources().getBoolean( when(mContext.getResources().getBoolean(
com.android.settings.R.bool.has_boot_sounds)).thenReturn(true); R.bool.has_boot_sounds)).thenReturn(true);
assertThat(mController.isAvailable()).isTrue(); assertThat(mController.isAvailable()).isTrue();
} }
@@ -70,15 +70,14 @@ public class BootSoundPreferenceControllerTest {
@Test @Test
public void isAvailable_noBootSounds_shouldReturnFale() { public void isAvailable_noBootSounds_shouldReturnFale() {
when(mContext.getResources().getBoolean( when(mContext.getResources().getBoolean(
com.android.settings.R.bool.has_boot_sounds)).thenReturn(false); R.bool.has_boot_sounds)).thenReturn(false);
assertThat(mController.isAvailable()).isFalse(); assertThat(mController.isAvailable()).isFalse();
} }
@Test @Test
public void displayPreference_bootSoundEnabled_shouldCheckedPreference() { public void displayPreference_bootSoundEnabled_shouldCheckedPreference() {
ShadowSystemProperties.native_set(BootSoundPreferenceController.PROPERTY_BOOT_SOUNDS, "1"); SystemProperties.set(BootSoundPreferenceController.PROPERTY_BOOT_SOUNDS, "true");
mController.displayPreference(mScreen); mController.displayPreference(mScreen);
verify(mPreference).setChecked(true); verify(mPreference).setChecked(true);
@@ -86,7 +85,7 @@ public class BootSoundPreferenceControllerTest {
@Test @Test
public void displayPreference_bootSoundDisabled_shouldUncheckedPreference() { public void displayPreference_bootSoundDisabled_shouldUncheckedPreference() {
ShadowSystemProperties.native_set(BootSoundPreferenceController.PROPERTY_BOOT_SOUNDS, "0"); SystemProperties.set(BootSoundPreferenceController.PROPERTY_BOOT_SOUNDS, "0");
mController.displayPreference(mScreen); mController.displayPreference(mScreen);
@@ -100,7 +99,7 @@ public class BootSoundPreferenceControllerTest {
mController.handlePreferenceTreeClick(mPreference); mController.handlePreferenceTreeClick(mPreference);
assertThat(SystemProperties.get( assertThat(SystemProperties.get(
BootSoundPreferenceController.PROPERTY_BOOT_SOUNDS, null)).isEqualTo("1"); BootSoundPreferenceController.PROPERTY_BOOT_SOUNDS, null)).isEqualTo("1");
} }
@Test @Test
@@ -110,6 +109,6 @@ public class BootSoundPreferenceControllerTest {
mController.handlePreferenceTreeClick(mPreference); mController.handlePreferenceTreeClick(mPreference);
assertThat(SystemProperties.get( assertThat(SystemProperties.get(
BootSoundPreferenceController.PROPERTY_BOOT_SOUNDS, null)).isEqualTo("0"); BootSoundPreferenceController.PROPERTY_BOOT_SOUNDS, null)).isEqualTo("0");
} }
} }

View File

@@ -42,6 +42,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -63,7 +64,7 @@ public class DeletedChannelsPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm);
shadowApplication.setSystemService(Context.USER_SERVICE, mUm); shadowApplication.setSystemService(Context.USER_SERVICE, mUm);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mController = new DeletedChannelsPreferenceController(mContext, mBackend); mController = new DeletedChannelsPreferenceController(mContext, mBackend);
} }

View File

@@ -62,7 +62,7 @@ public class DescriptionPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm);
shadowApplication.setSystemService(Context.USER_SERVICE, mUm); shadowApplication.setSystemService(Context.USER_SERVICE, mUm);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mController = spy(new DescriptionPreferenceController(mContext)); mController = spy(new DescriptionPreferenceController(mContext));
} }

View File

@@ -45,6 +45,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -68,7 +69,7 @@ public class HeaderPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm);
shadowApplication.setSystemService(Context.USER_SERVICE, mUm); shadowApplication.setSystemService(Context.USER_SERVICE, mUm);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
PreferenceFragmentCompat fragment = mock(PreferenceFragmentCompat.class); PreferenceFragmentCompat fragment = mock(PreferenceFragmentCompat.class);
when(fragment.getContext()).thenReturn(mContext); when(fragment.getContext()).thenReturn(mContext);
FragmentActivity activity = mock(FragmentActivity.class); FragmentActivity activity = mock(FragmentActivity.class);

View File

@@ -85,7 +85,7 @@ public class LightsPreferenceControllerTest {
// By default allow lights // By default allow lights
SettingsShadowResources.overrideResource( SettingsShadowResources.overrideResource(
com.android.internal.R.bool.config_intrusiveNotificationLed, true); com.android.internal.R.bool.config_intrusiveNotificationLed, true);
Settings.Secure.putInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 1); Settings.System.putInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 1);
} }
@Test @Test
@@ -107,7 +107,7 @@ public class LightsPreferenceControllerTest {
@Test @Test
public void testIsAvailable_notIfSettingNotAllowed() { public void testIsAvailable_notIfSettingNotAllowed() {
Settings.Secure.putInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 0); Settings.System.putInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 0);
NotificationBackend.AppRow appRow = new NotificationBackend.AppRow(); NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
NotificationChannel channel = new NotificationChannel("", "", IMPORTANCE_DEFAULT); NotificationChannel channel = new NotificationChannel("", "", IMPORTANCE_DEFAULT);
mController.onResume(appRow, channel, null, null); mController.onResume(appRow, channel, null, null);

View File

@@ -51,6 +51,7 @@ import org.junit.runner.RunWith;
import org.mockito.Answers; import org.mockito.Answers;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@@ -73,7 +74,7 @@ public class NotificationPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm);
shadowApplication.setSystemService(Context.USER_SERVICE, mUm); shadowApplication.setSystemService(Context.USER_SERVICE, mUm);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mController = new TestPreferenceController(mContext, mBackend); mController = new TestPreferenceController(mContext, mBackend);
} }

View File

@@ -138,14 +138,14 @@ public class PulseNotificationPreferenceControllerTest {
@Test @Test
public void isChecked_configOn_shouldReturnTrue() { public void isChecked_configOn_shouldReturnTrue() {
Settings.Secure.putInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 1); Settings.System.putInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 1);
assertThat(mController.isChecked()).isTrue(); assertThat(mController.isChecked()).isTrue();
} }
@Test @Test
public void isChecked_configOff_shouldReturnFalse() { public void isChecked_configOff_shouldReturnFalse() {
Settings.Secure.putInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 0); Settings.System.putInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 0);
assertThat(mController.isChecked()).isFalse(); assertThat(mController.isChecked()).isFalse();
} }
@@ -156,7 +156,7 @@ public class PulseNotificationPreferenceControllerTest {
assertThat(mController.isChecked()).isTrue(); assertThat(mController.isChecked()).isTrue();
assertThat( assertThat(
Settings.Secure.getInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 0)) Settings.System.getInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 0))
.isEqualTo(1); .isEqualTo(1);
} }
@@ -166,7 +166,7 @@ public class PulseNotificationPreferenceControllerTest {
assertThat(mController.isChecked()).isFalse(); assertThat(mController.isChecked()).isFalse();
assertThat( assertThat(
Settings.Secure.getInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 1)) Settings.System.getInt(mContext.getContentResolver(), NOTIFICATION_LIGHT_PULSE, 1))
.isEqualTo(0); .isEqualTo(0);
} }
} }

View File

@@ -59,6 +59,7 @@ import org.junit.runner.RunWith;
import org.mockito.Answers; import org.mockito.Answers;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@@ -90,7 +91,7 @@ public class SoundPreferenceControllerTest {
shadowApplication.setSystemService(Context.USER_SERVICE, mUm); shadowApplication.setSystemService(Context.USER_SERVICE, mUm);
SettingsShadowResources.overrideResource(com.android.internal.R.string.ringtone_silent, SettingsShadowResources.overrideResource(com.android.internal.R.string.ringtone_silent,
"silent"); "silent");
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mController = spy(new SoundPreferenceController( mController = spy(new SoundPreferenceController(
mContext, mFragment, mImportanceListener, mBackend)); mContext, mFragment, mImportanceListener, mBackend));
} }

View File

@@ -59,6 +59,7 @@ import org.mockito.Answers;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
@@ -91,7 +92,7 @@ public class VisibilityPreferenceControllerTest {
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm);
shadowApplication.setSystemService(Context.USER_SERVICE, mUm); shadowApplication.setSystemService(Context.USER_SERVICE, mUm);
shadowApplication.setSystemService(Context.DEVICE_POLICY_SERVICE, mDm); shadowApplication.setSystemService(Context.DEVICE_POLICY_SERVICE, mDm);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mController = spy(new VisibilityPreferenceController(mContext, mLockUtils, mBackend)); mController = spy(new VisibilityPreferenceController(mContext, mLockUtils, mBackend));
// by default the lockscreen is secure // by default the lockscreen is secure
@@ -202,7 +203,7 @@ public class VisibilityPreferenceControllerTest {
mController.updateState(pref); mController.updateState(pref);
ArgumentCaptor<CharSequence[]> argumentCaptor = ArgumentCaptor<CharSequence[]> argumentCaptor =
ArgumentCaptor.forClass(CharSequence[].class); ArgumentCaptor.forClass(CharSequence[].class);
verify(pref, times(1)).setEntryValues(argumentCaptor.capture()); verify(pref, times(1)).setEntryValues(argumentCaptor.capture());
assertFalse(toStringList(argumentCaptor.getValue()) assertFalse(toStringList(argumentCaptor.getValue())
.contains(String.valueOf(VISIBILITY_NO_OVERRIDE))); .contains(String.valueOf(VISIBILITY_NO_OVERRIDE)));
@@ -250,7 +251,7 @@ public class VisibilityPreferenceControllerTest {
mController.updateState(pref); mController.updateState(pref);
ArgumentCaptor<CharSequence[]> argumentCaptor = ArgumentCaptor<CharSequence[]> argumentCaptor =
ArgumentCaptor.forClass(CharSequence[].class); ArgumentCaptor.forClass(CharSequence[].class);
verify(pref, times(1)).setEntryValues(argumentCaptor.capture()); verify(pref, times(1)).setEntryValues(argumentCaptor.capture());
assertEquals(2, toStringList(argumentCaptor.getValue()).size()); assertEquals(2, toStringList(argumentCaptor.getValue()).size());
assertFalse(toStringList(argumentCaptor.getValue()) assertFalse(toStringList(argumentCaptor.getValue())
@@ -267,7 +268,7 @@ public class VisibilityPreferenceControllerTest {
mController.updateState(pref); mController.updateState(pref);
ArgumentCaptor<CharSequence[]> argumentCaptor = ArgumentCaptor<CharSequence[]> argumentCaptor =
ArgumentCaptor.forClass(CharSequence[].class); ArgumentCaptor.forClass(CharSequence[].class);
verify(pref, times(1)).setEntryValues(argumentCaptor.capture()); verify(pref, times(1)).setEntryValues(argumentCaptor.capture());
List<String> values = toStringList(argumentCaptor.getValue()); List<String> values = toStringList(argumentCaptor.getValue());
assertEquals(3, values.size()); assertEquals(3, values.size());

View File

@@ -47,6 +47,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
@@ -61,7 +62,8 @@ public class ZenFooterPreferenceControllerTest {
private Context mContext; private Context mContext;
@Mock @Mock
private PreferenceScreen mScreen; private PreferenceScreen mScreen;
@Mock NotificationManager mNotificationManager; @Mock
NotificationManager mNotificationManager;
private static final String PREF_KEY = "main_pref"; private static final String PREF_KEY = "main_pref";
@@ -69,7 +71,7 @@ public class ZenFooterPreferenceControllerTest {
public void setup() { public void setup() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
when(mNotificationManager.getNotificationPolicy()).thenReturn( when(mNotificationManager.getNotificationPolicy()).thenReturn(
mock(NotificationManager.Policy.class)); mock(NotificationManager.Policy.class));

View File

@@ -72,14 +72,14 @@ public class ZenModeAlarmsPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
mController = new ZenModeAlarmsPreferenceController(mContext, mock(Lifecycle.class)); mController = new ZenModeAlarmsPreferenceController(mContext, mock(Lifecycle.class));
ReflectionHelpers.setField(mController, "mBackend", mBackend); ReflectionHelpers.setField(mController, "mBackend", mBackend);
when(mPreferenceScreen.findPreference(mController.getPreferenceKey())) when(mPreferenceScreen.findPreference(mController.getPreferenceKey()))
.thenReturn(mockPref); .thenReturn(mockPref);
mController.displayPreference(mPreferenceScreen); mController.displayPreference(mPreferenceScreen);
} }
@@ -124,7 +124,7 @@ public class ZenModeAlarmsPreferenceControllerTest {
mController.onPreferenceChange(mockPref, allowAlarms); mController.onPreferenceChange(mockPref, allowAlarms);
verify(mBackend) verify(mBackend)
.saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS, allowAlarms); .saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS, allowAlarms);
} }
@Test @Test
@@ -133,6 +133,6 @@ public class ZenModeAlarmsPreferenceControllerTest {
mController.onPreferenceChange(mockPref, allowAlarms); mController.onPreferenceChange(mockPref, allowAlarms);
verify(mBackend) verify(mBackend)
.saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS, allowAlarms); .saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS, allowAlarms);
} }
} }

View File

@@ -86,7 +86,7 @@ public class ZenModeBehaviorFooterPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getZenModeConfig()).thenReturn(mZenModeConfig); when(mNotificationManager.getZenModeConfig()).thenReturn(mZenModeConfig);
@@ -95,7 +95,7 @@ public class ZenModeBehaviorFooterPreferenceControllerTest {
ReflectionHelpers.setField(mController, "mZenModeConfigWrapper", mConfigWrapper); ReflectionHelpers.setField(mController, "mZenModeConfigWrapper", mConfigWrapper);
when(mPreferenceScreen.findPreference(mController.getPreferenceKey())) when(mPreferenceScreen.findPreference(mController.getPreferenceKey()))
.thenReturn(mockPref); .thenReturn(mockPref);
mController.displayPreference(mPreferenceScreen); mController.displayPreference(mPreferenceScreen);
} }

View File

@@ -77,7 +77,7 @@ public class ZenModeButtonPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
mController = new ZenModeButtonPreferenceController(mContext, mock(Lifecycle.class), mController = new ZenModeButtonPreferenceController(mContext, mock(Lifecycle.class),
mock(FragmentManager.class)); mock(FragmentManager.class));

View File

@@ -79,13 +79,13 @@ public class ZenModeCallsPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mValues = mContext.getResources().getStringArray(R.array.zen_mode_contacts_values); mValues = mContext.getResources().getStringArray(R.array.zen_mode_contacts_values);
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
when(mBackend.getPriorityCallSenders()) when(mBackend.getPriorityCallSenders())
.thenReturn(NotificationManager.Policy.PRIORITY_SENDERS_STARRED); .thenReturn(NotificationManager.Policy.PRIORITY_SENDERS_STARRED);
when(mBackend.getContactsSummary(ZenModeBackend.SOURCE_NONE)) when(mBackend.getContactsSummary(ZenModeBackend.SOURCE_NONE))
.thenCallRealMethod(); .thenCallRealMethod();
when(mBackend.getContactsSummary(NotificationManager.Policy.PRIORITY_CATEGORY_CALLS)) when(mBackend.getContactsSummary(NotificationManager.Policy.PRIORITY_CATEGORY_CALLS))

View File

@@ -57,7 +57,7 @@ public class ZenModeDurationPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
mController = new ZenModeDurationPreferenceController(mContext, mock(Lifecycle.class)); mController = new ZenModeDurationPreferenceController(mContext, mock(Lifecycle.class));
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);

View File

@@ -29,6 +29,8 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.res.Resources; import android.content.res.Resources;
import androidx.fragment.app.FragmentActivity;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.SettingsShadowResources; import com.android.settings.testutils.shadow.SettingsShadowResources;
@@ -38,6 +40,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
import org.robolectric.shadows.ShadowToast; import org.robolectric.shadows.ShadowToast;
@@ -45,8 +48,6 @@ import org.robolectric.shadows.ShadowToast;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import androidx.fragment.app.FragmentActivity;
@RunWith(SettingsRobolectricTestRunner.class) @RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = SettingsShadowResources.SettingsShadowTheme.class) @Config(shadows = SettingsShadowResources.SettingsShadowTheme.class)
public class ZenModeEventRuleSettingsTest { public class ZenModeEventRuleSettingsTest {
@@ -69,7 +70,7 @@ public class ZenModeEventRuleSettingsTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mFragment = spy(new TestFragment()); mFragment = spy(new TestFragment());
mFragment.onAttach(application); mFragment.onAttach(application);

View File

@@ -70,7 +70,7 @@ public class ZenModeMediaPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
@@ -79,7 +79,7 @@ public class ZenModeMediaPreferenceControllerTest {
ReflectionHelpers.setField(mController, "mBackend", mBackend); ReflectionHelpers.setField(mController, "mBackend", mBackend);
when(mPreferenceScreen.findPreference(mController.getPreferenceKey())) when(mPreferenceScreen.findPreference(mController.getPreferenceKey()))
.thenReturn(mockPref); .thenReturn(mockPref);
mController.displayPreference(mPreferenceScreen); mController.displayPreference(mPreferenceScreen);
} }

View File

@@ -79,13 +79,13 @@ public class ZenModeMessagesPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mValues = mContext.getResources().getStringArray(R.array.zen_mode_contacts_values); mValues = mContext.getResources().getStringArray(R.array.zen_mode_contacts_values);
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
when(mBackend.getPriorityMessageSenders()) when(mBackend.getPriorityMessageSenders())
.thenReturn(NotificationManager.Policy.PRIORITY_SENDERS_STARRED); .thenReturn(NotificationManager.Policy.PRIORITY_SENDERS_STARRED);
when(mBackend.getContactsSummary(ZenModeBackend.SOURCE_NONE)) when(mBackend.getContactsSummary(ZenModeBackend.SOURCE_NONE))
.thenCallRealMethod(); .thenCallRealMethod();
when(mBackend.getContactsSummary(NotificationManager.Policy.PRIORITY_CATEGORY_MESSAGES)) when(mBackend.getContactsSummary(NotificationManager.Policy.PRIORITY_CATEGORY_MESSAGES))

View File

@@ -41,6 +41,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
@@ -64,7 +65,7 @@ public class ZenModePreferenceControllerTest {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mController = new ZenModePreferenceController(mContext, KEY_ZEN_MODE); mController = new ZenModePreferenceController(mContext, KEY_ZEN_MODE);
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
mSummaryBuilder = spy(new ZenModeSettings.SummaryBuilder(mContext)); mSummaryBuilder = spy(new ZenModeSettings.SummaryBuilder(mContext));

View File

@@ -72,7 +72,7 @@ public class ZenModeRemindersPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
@@ -80,7 +80,7 @@ public class ZenModeRemindersPreferenceControllerTest {
ReflectionHelpers.setField(mController, "mBackend", mBackend); ReflectionHelpers.setField(mController, "mBackend", mBackend);
when(mPreferenceScreen.findPreference(mController.getPreferenceKey())) when(mPreferenceScreen.findPreference(mController.getPreferenceKey()))
.thenReturn(mockPref); .thenReturn(mockPref);
mController.displayPreference(mPreferenceScreen); mController.displayPreference(mPreferenceScreen);
} }
@@ -127,7 +127,7 @@ public class ZenModeRemindersPreferenceControllerTest {
mController.onPreferenceChange(mockPref, allow); mController.onPreferenceChange(mockPref, allow);
verify(mBackend) verify(mBackend)
.saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_REMINDERS, allow); .saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_REMINDERS, allow);
} }
@Test @Test
@@ -136,6 +136,6 @@ public class ZenModeRemindersPreferenceControllerTest {
mController.onPreferenceChange(mockPref, allow); mController.onPreferenceChange(mockPref, allow);
verify(mBackend) verify(mBackend)
.saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_REMINDERS, allow); .saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_REMINDERS, allow);
} }
} }

View File

@@ -71,7 +71,7 @@ public class ZenModeRepeatCallersPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
@@ -142,7 +142,8 @@ public class ZenModeRepeatCallersPreferenceControllerTest {
mController.onPreferenceChange(mockPref, allow); mController.onPreferenceChange(mockPref, allow);
verify(mBackend) verify(mBackend)
.saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_REPEAT_CALLERS, allow); .saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_REPEAT_CALLERS,
allow);
} }
@Test @Test
@@ -151,6 +152,7 @@ public class ZenModeRepeatCallersPreferenceControllerTest {
mController.onPreferenceChange(mockPref, allow); mController.onPreferenceChange(mockPref, allow);
verify(mBackend) verify(mBackend)
.saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_REPEAT_CALLERS, allow); .saveSoundPolicy(NotificationManager.Policy.PRIORITY_CATEGORY_REPEAT_CALLERS,
allow);
} }
} }

View File

@@ -40,6 +40,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
import org.robolectric.shadows.ShadowToast; import org.robolectric.shadows.ShadowToast;
@@ -66,7 +67,7 @@ public class ZenModeScheduleRuleSettingsTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mFragment = spy(new TestFragment()); mFragment = spy(new TestFragment());
mFragment.onAttach(application); mFragment.onAttach(application);

View File

@@ -88,12 +88,12 @@ public class ZenModeSettingsFooterPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getZenModeConfig()).thenReturn(mZenModeConfig); when(mNotificationManager.getZenModeConfig()).thenReturn(mZenModeConfig);
mController = mController =
new ZenModeSettingsFooterPreferenceController(mContext, mock(Lifecycle.class)); new ZenModeSettingsFooterPreferenceController(mContext, mock(Lifecycle.class));
ReflectionHelpers.setField(mZenModeConfig, AUTOMATIC_RULES_FIELD, mInjectedAutomaticRules); ReflectionHelpers.setField(mZenModeConfig, AUTOMATIC_RULES_FIELD, mInjectedAutomaticRules);
ReflectionHelpers.setField(mController, "mZenModeConfigWrapper", mConfigWrapper); ReflectionHelpers.setField(mController, "mZenModeConfigWrapper", mConfigWrapper);
@@ -276,7 +276,7 @@ public class ZenModeSettingsFooterPreferenceControllerTest {
injectedManualRule.conditionId = mock(Uri.class); injectedManualRule.conditionId = mock(Uri.class);
when(mConfigWrapper.parseManualRuleTime(injectedManualRule.conditionId)).thenReturn(time); when(mConfigWrapper.parseManualRuleTime(injectedManualRule.conditionId)).thenReturn(time);
when(mConfigWrapper.getFormattedTime(time, mContext.getUserId())) when(mConfigWrapper.getFormattedTime(time, mContext.getUserId()))
.thenReturn(timePlaceholder); .thenReturn(timePlaceholder);
ReflectionHelpers.setField(mZenModeConfig, MANUAL_RULE_FIELD, injectedManualRule); ReflectionHelpers.setField(mZenModeConfig, MANUAL_RULE_FIELD, injectedManualRule);
} }

View File

@@ -45,6 +45,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowApplication;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
@@ -78,7 +79,7 @@ public class ZenModeStarredContactsPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
when(testIntent.resolveActivity(any())).thenReturn(mComponentName); when(testIntent.resolveActivity(any())).thenReturn(mComponentName);
@@ -163,8 +164,8 @@ public class ZenModeStarredContactsPreferenceControllerTest {
// expected - no null values // expected - no null values
List<String> contacts = mMessagesController.getStarredContacts(testCursorWithNullValues); List<String> contacts = mMessagesController.getStarredContacts(testCursorWithNullValues);
for (int i = 0 ; i < contacts.size(); i++) { for (String contact : contacts) {
assertThat(contacts.get(i)).isNotNull(); assertThat(contact).isNotNull();
} }
} }
@@ -183,6 +184,7 @@ public class ZenModeStarredContactsPreferenceControllerTest {
doAnswer(new Answer<Boolean>() { doAnswer(new Answer<Boolean>() {
int count = 0; int count = 0;
@Override @Override
public Boolean answer(InvocationOnMock invocation) throws Throwable { public Boolean answer(InvocationOnMock invocation) throws Throwable {
if (count < size) { if (count < size) {

View File

@@ -69,7 +69,7 @@ public class ZenModeSystemPreferenceControllerTest {
ShadowApplication shadowApplication = ShadowApplication.getInstance(); ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager); shadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNotificationManager);
mContext = shadowApplication.getApplicationContext(); mContext = RuntimeEnvironment.application;
mContentResolver = RuntimeEnvironment.application.getContentResolver(); mContentResolver = RuntimeEnvironment.application.getContentResolver();
when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy); when(mNotificationManager.getNotificationPolicy()).thenReturn(mPolicy);
mController = new ZenModeSystemPreferenceController(mContext, mock(Lifecycle.class)); mController = new ZenModeSystemPreferenceController(mContext, mock(Lifecycle.class));

Some files were not shown because too many files have changed in this diff Show More