Robolectric 4.0
Robolectric 4.0 brings support for the Android P (SDK 28) release, new and improved support and testing APIs for dozens of Android classes, initial support for some androidx-test APIs, and a complete rewrite of the resource handling code making it behave much more like a real Android device.
With the major version number bump to 4.0, we're making changes to some public APIs, detailed below. Check out the migration notes and use the new automated migration tool to help convert your existing tests to be compatible with Robolectric 4.0.
API Changes
- Most
@Implementationmethods in shadow classes are nowprotectedinstead ofpublic. Tests should always prefer to call SDK methods directly on Android classes rather than on their shadows [issue #4007]. RuntimeEnvironment.applicationhas been deprecated, useandroidx.test.core.app.ApplicationProvider.getApplicationContext()instead.AutoCloseableis now supported. In earlier versions of Robolectric, try-with-resources blocks would fail to callclose()on the resource.- Bumped Android P to build 4913185.
Resources
In conjunction with Android Studio 3.2, Robolectric can now use resources processed using the Android build toolchain, and loads and handles those resources using the same logic as on an actual Android device. Robolectric’s old idiosyncratic resource handling mode is still available for projects not yet using the latest version of the build toolchain, but is now deprecated.
New and improved SDK support and testing APIs for numerous Android classes, including:
ActivityManager.getAppTasks()ApplicationPackageManagercontent providers,canRequestPackageInstalls()AppOpsManagerAsyncQueryHandlerAudioManager.getActivePlaybackConfiguration()BackupManagerBluetoothAdapterprofile connection state and bond stateBuild.getSerial()CameraManagerandCameraCharacteristicsCamera.Parameterspreview sizesCarrierConfigManager.getConfigForSubId()ConnectivityManagersupport forNetworkCapabilities,requestNetwork().ContentResolver.openOutputStream(), 'getSyncAdapterTypes()'Context.bindServiceAsUser()DevicePolicyManager.setUserProvisioningState()EuiccManagerFontFamily- Improvements to
AccessibilityNodeInfo NotificationManagersupport forAutomaticZenRulesPackageManager.checkPermission()checksPackageInfo.requestedPermissionsFlagsto determine if a permission is granted.Path,PathMeasure, andPathParserSensorManagerService.stopSelfResult()ShadowSensor.newInstance()SmsSoundPoolnow records more details whenplay()is called.StorageManagertest API for adding volumes.SubscriptionManager.getActiveSubscriptionInfoForSimSlotIndex(),getActiveSubscriptionInfoCount()etc., 'getDefaultSubscriptionId()'SystemClock.elapsedRealtimeNanos()andcurrentNetworkTimeMillis()TelecomManager.silenceRinger()TelephonyManager.getSubscriberId(),getSimSerialNumber(), 'getVoiceNetworkType()'TextToSpeechTileandTileServiceminimal implementationTimeZoneFinderUsbManagerUserManagernow supports multiple users.UserStatsManagertest API:ShadowUserStatsManager.simulateTimeChange(); useEventBuildercan be used to return arbitrary eventsVMRuntime.is64Bit(),ShadowVMRuntime.setIs64Bit(),ShadowBuild.setSupported64BitAbis()WebStorageWebView.saveState()andrestoreState()WifiManager.connect(int, ActionListener)- Fixed a bug in
RoboCursor.getLong(). - Fixed a deadlock related to saving preferences.
- Improved support for Java 9.
- Fixes to
Looper.myLooper() - Support for color gamut and HDR in
@Config(qualifiers). - Added subscribe and search functionality to
ShadowMediaBrowserCompat. Also added easy ways to createMediaItems and get all createdMediaItems with their parent-child relationships [thanks Jehron Petty and Noah Luddy!].getRoot(),getItem(),subscribe(), andsearch()can only be called successfully afterShadowMediaBroswserCompat.connect()is called.- The default root id is
root_id. This is what will be returned bygetRoot()by default. The root id can be changed withsetRootId(). Note that if the root is created withcreateMediaItem(),setRootId()must also be called with the samemediaId. - There is no
getSessionToken()method inShadowMediaBrowserCompat. Follow issue #3962 for updates.
Features
- Support for the Android 28 API [Issue #3933]
- Add errorprone/auto-refactoring support [Issue #3944]
- Verify shadow
@Implementationmethods against SDKs [Issue #3952] - Support Espresso typeText [Issue #3919]
- Add SupportFragmentController#setupFragment() [Issue #3911]
- Shadow get/setNotificationPolicy on NotificationManager [Issue #3911]
- Adds a simple Shadow for JobService so classes that extend it can call jobFinished() without crashing. [Issue #3911]
- Add createSensorEvent and sendSensorEventToListeners to ShadowSensorManager [Issue #3911]
- Make the result of WifiScanner#startScan() configurable. [Issue #3911]
- Add functionality for setting the unbadged application icon in ShadowPackageManager [Issue #3919]
- Support OnAlarmListener call in ShadowAlarmManager [Issue #3919]
- Add ParameterizedRobolectricTestRunner#parameter annotation and remove dependency on XStream [Issue #3919]
- Support CookieManager.removeAllCookies. [Issue #3919]
- Add overloads to PendingIntent.send [Issue #3919]
- Support retrieving the last message sent via Messenger [Issue #3919]
- Add implementation for getAppStandbyBuckets and setAppStandbyBuckets to ShadowUsageStatsManager [Issue #3919]
- Adding error behavior to ShadowGeocoder. [Issue #3919]
- Add basic GLES20 support. [Issue #3924], [Issue #3944]
- Add support for new LocationManager API in Android P [Issue #3924]
- Add support to ShadowPowerManager to capture rebooting. [Issue #3924]
- Add support for Parcel.read/writeBlob [Issue #3924]
- Improve ShadowSoundPool adding the ability to query played sounds. [Issue #3944]
- Add method to override system properties [Issue #3944]
- Add BluetoothDevice#getUuids/setUuids [Issue #3944]
- Enhance support for BluetoothGatt [Issue #3944]
- Implement the newer AudioManager request and abandon audio focus api [Issue #3944]
- Add ShadowPackageManager#addSystemSharedLibraryName [Issue #3944]
- Add setMode and checkOpNotThrow (hidden) APIs to ShadowAppOpsManager [Issue #3944]
- Update ShadowDebug to allow for method tracing. [Issue #3944]
- Add setTimeZone method to ShadowAlarmManager [Issue #3944]
- Add ShadowVisualVoicemailSms [Issue #3944]
- Add scrollBy methods to ShadowView and ShadowScrollView [Issue #3944]
- Add ShadowEventLog and ShadowProcess.setUid() [Issue #3944]
- Add a Shadow class for MediaBrowserCompat. [Issue #3944]
- Support ConnectivityManager#reportNetworkConnectivity [Issue #3944]
- Add shadow for DropboxManager. [Issue #3944]
- Add support for DisplayManager#setDisplaySaturation [Issue #3952]
- Add scrollBy methods to ShadowView and ShadowScrollView [Issue #3952]
- Add shadow for UsageStatsManager.queryUsageStats() and a builder for UsageStats. [Issue #3952]
- Extend ShadowNfcAdapter to verify ndefPushMessage and emulate absence of NFC hardware [Issue #3952]
- Improve fidelity of WifiInfo by removing shadows in favor of using real Android code. [Issue #3911]
- Add a Shadow class for MediaControllerCompat. [Issue #3956]
- Add ShadowNotificationManager#setNotificationPolicyAccessGranted(float) [Issue #3956]
- Add support for isSystemUser to ShadowUserManager. [Issue #3956]
- Adding a basic Shadow for the CaptioningManager. [Issue #3956]
- Add layerType to ShadowView [Issue #3956]
- Added support for
androidx.test'sActivityScenarioAPI. - Fixes for
ShadowBitmap.(set|is)Premultiplied()andShadowWebView.copyBackForwardList()
Bug fixes
- Implement ShadowDevicePolicyManager#setPackagesSuspended correctly. [Issue #3911]
- Add a NoOp implementation of NfcAdapter#setOnNdefPushCompleteCallback. [Issue #3911]
- Fix string HTML attributes in binary resources. [Issue #3911]
- Avoid throwing in Bitmap#reconfigure for non-native backed Bitmaps. [Issue #3911]
- Overriding getActivityIntent in ActivityTestRule has no effect [Issue #3918]
- Improved handling of lockTaskMode that works now across activities and ActivityManager. [Issue #3924]
- Fix NPEs when calling Surface#release and getString [Issue #3924]
- Enhance TelephonyManager support [Issue #3944]
- Set DataSource in ShadowMediaPlayer.create() [Issue #3944]
- Fix signature of ShadowAccessibilityNodeInfo.setTraversalBefore()/After [Issue #3944]
- Added a few methods to the ShadowCamera to prevent an NPE in Camera.Parameters and execute callbacks passed to takePicture [Issue #3952]
- Improved package lost sequence number check [Issue #3956]
- Don't modify PendingIntent extras upon sending it [Issue #2503]
- Fix
ActivityScenariosupport [Issue #4022] View.post()andpostDelayed(). now more properly returntrue, which fixes a bug that sometimes caused duplicate tap events to be delivered.
Deprecations
- Deprecate SupportFragmentTestUtil [Issue #3911]
ShadowApplication.getInstance()ShadowLooper.getShadowMainLooper()Config(packageName)
Removals
- Remove ShadowApplication.getApplicationContext() in favor of RuntimeEnvironment#application [Issue #3911]
- Remove unused ShadowFrameLayout [Issue #3924]
- Remove @implementation methods from ShadowViewGroup that are not necessary as we can just call the real implementation instead. [Issue #3924]
- Delete shadows.MotionEventBuilder in favor of using androidx.test.core.view.MotionEventBuilder [Issue #3956]
ShadowContentResolver.clearContentObservers()- Replace
ShadowAlertDialog.getShadowAlertController()withgetAlertController() - Various deprecated
RobolectricTestRunnermethods ShadowAccountManager.get()ShadowKeyguardManager.setinRestrictedInputMode()ShadowNetworkInfo.newInstance()- Replace
ShadowGradientDrawable.getColor()withgetLastSetColor()
Known Issues
- Robolectric 4 does not work on Windows [issue #3955].
- Android Gradle Plugin may report the following warning, which may be safely ignored:
WARNING: The option setting 'android.enableUnitTestBinaryResources=true' is experimental and unsupported.
Use Robolectric:
testCompile "org.robolectric:robolectric:4.0"Find more details here. Report issues here. Enjoy!