VibrationHelper { @SuppressLint("MissingPermission") public static void vibrate(Context context, int duration) { if (hasVibrationPermission(context)) { ((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(duration); } }  @SuppressLint("MissingPermission") static void vibrate(Context context, int duration); static boolean hasVibrationPermission(Context context);  }
@Test public void vibrate_callsVibrateIfHasVibratePermissionIsTrue() { PackageManager packageManager = mock(PackageManager.class); when(packageManager.checkPermission(eq(Manifest.permission.VIBRATE), anyString())) .thenReturn(PackageManager.PERMISSION_GRANTED); Vibrator vibrator = mock(Vibrator.class); Context context = mock(Context.class); when(context.getPackageManager()).thenReturn(packageManager); when(context.getSystemService(Context.VIBRATOR_SERVICE)).thenReturn(vibrator); VibrationHelper.vibrate(context, 1000); verify(vibrator).vibrate(1000); }
@Test public void vibrate_doesNotCallVibrateIfHasVibratePermissionIsFalse() { PackageManager packageManager = mock(PackageManager.class); when(packageManager.checkPermission(eq(Manifest.permission.VIBRATE), anyString())) .thenReturn(PackageManager.PERMISSION_DENIED); Vibrator vibrator = mock(Vibrator.class); Context context = mock(Context.class); when(context.getPackageManager()).thenReturn(packageManager); when(context.getPackageName()).thenReturn("com.braintreepayments.cardform.test"); when(context.getSystemService(Context.VIBRATOR_SERVICE)).thenReturn(vibrator); VibrationHelper.vibrate(context, 1000); verifyZeroInteractions(vibrator); }