Android Unit Testing Framework


Build Status GitHub release

Robolectric is the industry-standard unit testing framework for Android. With Robolectric, your tests run in a simulated Android environment inside a JVM, without the overhead of an emulator.


Here's an example of a simple test written using Robolectric:

public class MyActivityTest {

  public void clickingButton_shouldChangeResultsViewText() throws Exception {
    Activity activity = Robolectric.setupActivity(MyActivity.class);

    Button button = (Button) activity.findViewById(;
    TextView results = (TextView) activity.findViewById(;

    assertThat(results.getText().toString(), equalTo("Testing Android Rocks!"));

For more information about how to install and use Robolectric on your project, extend its functionality, and join the community of contributors, please visit


Starting a New Project

If you'd like to start a new project with Robolectric tests you can refer to deckard (for either maven or gradle) as a guide to setting up both Android and Robolectric on your machine.


testImplementation "org.robolectric:robolectric:4.5.1"

Building And Contributing

Robolectric is built using Gradle. Both IntelliJ and Android Studio can import the top-level build.gradle file and will automatically generate their project files from it.

Robolectric supports running tests against multiple Android API levels. The work it must do to support each API level is slightly different, so its shadows are built separately for each. To build shadows for every API version, run:

./gradlew clean assemble testClasses --parallel

Using Snapshots

If you would like to live on the bleeding edge, you can try running against a snapshot build. Keep in mind that snapshots represent the most recent changes on master and may contain bugs.


repositories {
    maven { url "" }

dependencies {
    testImplementation "org.robolectric:robolectric:4.6-SNAPSHOT"
  • Robolectric cannot download artifacts - all tests fail

    Robolectric cannot download artifacts - all tests fail


    [Robolectric] : sdk=28; resources=BINARY Downloading from maven Downloading: org/robolectric/android-all/10-robolectric-5803371/android-all-10-robolectric-5803371.pom from repository sonatype at Error transferring file: Error constructing implementation (algorithm: Default, provider: SunJSSE, class:$DefaultSSLContext) [WARNING] Unable to get resource 'org.robolectric:android-all:pom:10-robolectric-5803371' from repository sonatype ( Error transferring file: Error constructing implementation (algorithm: Default, provider: SunJSSE, class:$DefaultSSLContext) Downloading: org/robolectric/android-all/10-robolectric-5803371/android-all-10-robolectric-5803371.pom from repository central at Error transferring file: Server returned HTTP response code: 501 for URL: [WARNING] Unable to get resource 'org.robolectric:android-all:pom:10-robolectric-5803371' from repository central ( Error transferring file: Server returned HTTP response code: 501 for URL: Downloading: org/robolectric/android-all/10-robolectric-5803371/android-all-10-robolectric-5803371.jar from repository sonatype at Error transferring file: Error constructing implementation (algorithm: Default, provider: SunJSSE, class:$DefaultSSLContext) [WARNING] Unable to get resource 'org.robolectric:android-all:jar:10-robolectric-5803371' from repository sonatype ( Error transferring file: Error constructing implementation (algorithm: Default, provider: SunJSSE, class:$DefaultSSLContext) Downloading: org/robolectric/android-all/10-robolectric-5803371/android-all-10-robolectric-5803371.jar from repository central at Error transferring file: Server returned HTTP response code: 501 for URL: [WARNING] Unable to get resource 'org.robolectric:android-all:jar:10-robolectric-5803371' from repository central ( Error transferring file: Server returned HTTP response code: 501 for URL:

    Unable to resolve artifact: Missing:

    1. org.robolectric:android-all:jar:10-robolectric-5803371

    Steps to Reproduce

    Create a unit test with RobolectricTestRunner

    Robolectric Version


    opened by wongk 93
  • Redesign database related shadows

    Redesign database related shadows

    Removes a lot of shadows connected with SQLiteDatabase and Cursor, makes Robolectric behaviour much closer to how real Android behaves.

    Instead of a bunch of removed shadows we introduce implementations of SQLiteConntection and CursorWindow based on sqlite4java. This approach let us drop a lot of shadowing code and use real Android classes. However both implemented classes belong to a hidden Android API, which means we should be careful when add some new Android API level to what is supported by Robolectric (especially adding 2.x APIs).

    Worth to mention in release notes:

    • SQLiteDatabase#openDatabase opens on-disk database until its path parameter is set with ":memory:" value;
    • DatabaseConfig annotation is gone
    • some methods from the shadowed db are gone:
      • in SQLiteDatabase: setThrowOnInsert, hasOpenCursors, getQuerySql, getConnection

    History notes

    Some time ago I faced with some inconsistencies in shadows of cursors and started digging first removing shadow of matrix cursor and then... This request is not a merge candidate right now but rather a proposal.

    I'm playing with removing cursor shadows completely and shadowing only SQLiteConnection and CursorWindow instead (ShadowSQLiteConnection, ShadowCursorWindow).

    I've already made some progress in this direction and have some of database related tests passing. And now I'd like someone from the main team to take a look at the approach and start discussion. Perhaps it's not the way worth to be implemented.

    Currently I have 2 main points that do not allow me to sleep sweetly:

    So please take a look and tell what you think: should I go on or would I rather stop, delete this branch, and forget :).

    opened by roman-mazur 60
  • Apple Silicon support

    Apple Silicon support


    When perform robolectric test on Apple silicon, following error is raised

        Caused by: com.almworks.sqlite4java.SQLiteException: [-91] cannot load library: java.lang.UnsatisfiedLinkError: /private/var/folders/xp/t20n_5q54v9d7dz1rt9bk9k40000gp/T/1616114208715-0/libsqlite4java.dylib: dlopen(/private/var/folders/xp/t20n_5q54v9d7dz1rt9bk9k40000gp/T/1616114208715-0/libsqlite4java.dylib, 1): no suitable image found.  Did find:
        	/private/var/folders/xp/t20n_5q54v9d7dz1rt9bk9k40000gp/T/1616114208715-0/libsqlite4java.dylib: no matching architecture in universal wrapper
        	/private/var/folders/xp/t20n_5q54v9d7dz1rt9bk9k40000gp/T/1616114208715-0/libsqlite4java.dylib: no matching architecture in universal wrapper
        	at com.almworks.sqlite4java.SQLite.loadLibrary(
        	at com.almworks.sqlite4java.SQLite.getSQLiteVersion(
        	at org.robolectric.shadows.util.SQLiteLibraryLoader.loadFromDirectory(
        	at org.robolectric.shadows.util.SQLiteLibraryLoader.doLoad(
        	at org.robolectric.shadows.util.SQLiteLibraryLoader.load(
        	at org.robolectric.shadows.ShadowSQLiteConnection.nativeOpen(
        	at org.robolectric.shadows.ShadowSQLiteConnection.nativeOpen(
        	at android.database.sqlite.SQLiteConnection.nativeOpen(
        Caused by: java.lang.UnsatisfiedLinkError: /private/var/folders/xp/t20n_5q54v9d7dz1rt9bk9k40000gp/T/1616114208715-0/libsqlite4java.dylib: dlopen(/private/var/folders/xp/t20n_5q54v9d7dz1rt9bk9k40000gp/T/1616114208715-0/libsqlite4java.dylib, 1): no suitable image found.  Did find:
        	/private/var/folders/xp/t20n_5q54v9d7dz1rt9bk9k40000gp/T/1616114208715-0/libsqlite4java.dylib: no matching architecture in universal wrapper
        	/private/var/folders/xp/t20n_5q54v9d7dz1rt9bk9k40000gp/T/1616114208715-0/libsqlite4java.dylib: no matching architecture in universal wrapper
        	at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method)
        	at java.base/java.lang.ClassLoader$NativeLibrary.load(
        	at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(
        	at java.base/java.lang.ClassLoader.loadLibrary0(
        	at java.base/java.lang.ClassLoader.loadLibrary(
        	at java.base/java.lang.Runtime.load0(
        	at java.base/java.lang.System.load(
        	at com.almworks.sqlite4java.Internal.tryLoadFromPath(
        	at com.almworks.sqlite4java.Internal.loadLibraryX(
        	at com.almworks.sqlite4java.SQLite.loadLibrary(
        	... 36 more

    Robolectric & Android Version

    JVM : Jetbrains Runtime from Intellij IDEA 2020.3.2 ( OpenJDK 64-Bit Server VM JBR- (build, mixed mode) ) Robolectric : 4.5.1 Android Compile SDK : 30

    opened by ganadist 59
  • Robolectric crashes with new VectorDrawableCompat

    Robolectric crashes with new VectorDrawableCompat

    When AppCompat tries to create a drawable from a given vector, Robolectric tests fail with the following exception:

    Caused by: org.xmlpull.v1.XmlPullParserException: XML file build/intermediates/res/merged/world/debug/drawable-anydpi-v21/abc_ic_ab_back_material.xml line #-1 (sorry, not yet implemented): invalid drawable tag vector
        at android.content.res.Resources.loadDrawable(
        ... 57 more

    Happens regardless of whether or not support vectors are enabled as specified here:

    // Gradle Plugin 2.0+  
     android {  
       defaultConfig {  
         vectorDrawables.useSupportLibrary = true  

    Relevant exception higher up:

    Caused by: android.content.res.Resources$NotFoundException: File build/intermediates/res/merged/world/debug/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020016
        at android.content.res.Resources.loadDrawable(
        at org.robolectric.util.ReflectionHelpers.callInstanceMethod(
        at org.robolectric.internal.Shadow.directlyOn(
        at org.robolectric.shadows.ShadowResources.loadDrawable(
        at android.content.res.Resources.loadDrawable(
        at android.content.res.Resources.getDrawable(
        at android.view.LayoutInflater.createView(
        at android.view.LayoutInflater.createViewFromTag(
        at android.view.LayoutInflater.rInflate(
        at android.view.LayoutInflater.rInflate(
        at android.view.LayoutInflater.inflate(
        at android.view.LayoutInflater.inflate(
        at android.view.LayoutInflater.inflate(

    AppCompat does some working around for vector drawables via its ResourcesWrapper and ContextWrapper classes, I think the solution for this is that Robolectric needs to work with this. See the bottom of

    opened by ZacSweers 57
  • OutOfMemoryError PermGen space and hanging builds

    OutOfMemoryError PermGen space and hanging builds

    I have a suite consisting of almost 2000 tests that work with Robolectric 2.4. I have started updating the suite to work with 3.0-rc2 but I can only run about ~700 tests before they fail with an OutOfMemoryError or hang. It seems that once I reach a certain size, the tests will fail. For example I will run X tests successfully, then I will add a few more test classes and the suite will fail. If I leave the newly added classes and remove some of the classes known to be successful, I can get a successful build again.

    The conversion for the majority of tests was just a matter of using the RobolectricGradleTestRunner, adding @Config line and fixing references to Robolectric classes that were moved. Continuing to use RobolectricTestRunner instead of RobolectricGradleTestRunner fails in similar ways.

    The following jvmargs are set in the file. Increasing the memory options does not help: org.gradle.jvmargs=-Xmx1024m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

    There are a few failure scenarios I have seen:

    • Test execution hang with no output

    • "OutOfMemoryError: PermGen space" error followed by gradle stacktrace

    • One of the above or just test failure followed by a different class loading error each time: [ERROR] couldn't load roboguice.activity.RoboActivity in org.robolectric.internal.bytecode.InstrumentingClassLoader@4d0ed336

      [ERROR] couldn't load android.content.Context in org.robolectric.internal.bytecode.InstrumentingClassLoader@3e1cbf2e

      [ERROR] couldn't load org.bouncycastle.jce.provider.BouncyCastleProvider in org.robolectric.internal.bytecode.InstrumentingClassLoader@6243e098

    In all cases, just removing a few test classes will allow the tests to succeed.

    Given I have a suite of testcases that work with 2.4 and work with 3.0-rc2 in batches of ~700 tests, It seems to point to something in the 3.0 changes that are causing these OOM errors.

    opened by cameocoder 49
  • Still get java.lang.RuntimeException: Stub! in Robolectric 2.2

    Still get java.lang.RuntimeException: Stub! in Robolectric 2.2

    I have a fairly complicated app that I'm trying to use with Robolectric 2.2. I've added the robolectric jar to the top of my classpath in IntelliJ but I still get:

    Caused by: java.lang.RuntimeException: Stub! at Source) at ... 31 more

    My classpath is: robolectric junit-4.10 app dependencies

    I've also tried: junit-4.10 robolectric app dependencies

    I use this ivv.xml to retreive my dependencies:

    <ivy-module version="2.0">
        <info organisation="" module="unit-test" />
            <conf name="binaries" description="binary jars" />
            <dependency org="org.robolectric" name="robolectric" rev="2.2" conf="binaries->default" />
            <dependency org="jmock" name="jmock" rev="1.2.0" conf="binaries->default" />

    and that brings down all of these jars which I add to my class path:

    ant-launcher.jar        commons-codec.jar       maven-artifact-manager.jar  nekohtml.jar            wagon-file.jar
    ant.jar             commons-logging.jar     maven-artifact.jar      objenesis.jar           wagon-http-lightweight.jar
    asm-analysis.jar        fest-reflect.jar        maven-error-diagnostics.jar plexus-container-default.jar    wagon-http-shared.jar
    asm-commons.jar         fest-util.jar           maven-model.jar         plexus-interpolation.jar    wagon-provider-api.jar
    asm-tree.jar            httpclient.jar          maven-plugin-registry.jar   plexus-utils.jar        xercesMinimal.jar
    asm-util.jar            httpcore.jar            maven-profile.jar       robolectric.jar
    asm.jar             jmock.jar           maven-project.jar       sqlite-jdbc.jar
    backport-util-concurrent.jar    junit.jar           maven-repository-metadata.jar   support-v4.jar
    classworlds.jar         maven-ant-tasks.jar     maven-settings.jar      vtd-xml.jar

    I'm using Robolectric 2.2 with the latest EAP IntelliJ. I noted that IntelliJ EAP was using the project root as a default for the working dir and have fixed this to use the module dir. Prior to that I could run my test without getting this error but it was having trouble finding resources. Please help!

    opened by cliff76 49
  • Supporting nativeruntime building for Windows

    Supporting nativeruntime building for Windows

    This issue is used to track Windows building support for nativeruntime.

    Previous discussions are here:

    opened by utzcoz 48
  • FileNotFoundException when opening AssetFileDescriptor

    FileNotFoundException when opening AssetFileDescriptor


    One of the functions in my unit tests wants to open an AssetFileDescriptor. I tried to use RuntimeEnvironment.systemContext and ApplicationProvider.getApplicationContext() interchangeably.

    1. Using RuntimeEnvironment.systemContext gives me birds_or_cats_or_whatever
          at org.robolectric.shadows.ShadowArscAssetManager9.nativeOpenAssetFd(
          at android.content.res.AssetManager.nativeOpenAssetFd(
          at android.content.res.AssetManager.openFd(
    2. Using ApplicationProvider.getApplicationContext() gives me This file can not be opened as a file descriptor; it is probably compressed
          at org.robolectric.shadows.ShadowArscAssetManager9.ReturnParcelFileDescriptor(
          at org.robolectric.shadows.ShadowArscAssetManager9.nativeOpenAssetFd(
          at android.content.res.AssetManager.nativeOpenAssetFd(
          at android.content.res.AssetManager.openFd(

    The latter error was more descriptive. Following the message from the stack-trace, I tried to disable the aapt resource compression for all resources using the following Gradle config but with no luck. Regardless of the compression settings, I am able to open an AssetInputStream to a resource with ApplicationProvider.getApplicationContext() context but unable to open a file descriptor to the same resource.

    android {
      aaptOptions {
        noCompress ''

    Steps to Reproduce

    Already covered

    Robolectric & Android Version

    • Android SDK 29
    • Robolectric 4.3.1
    • Tests are targeted for SDK 21 and 28

    Link to a public git repo demonstrating the problem:

    You can play around with this test. It highlights the problem.

    Links to

    opened by ashutoshgngwr 48
  • ViewPager IllegalStateException

    ViewPager IllegalStateException

    I have a problem similar to

    The stacktrace is the same, but the code is not. In my case I start a Fragment using FragmentTestUtil. That Fragment calls ViewPager.setCurrentItem when it has been started, so I can't use this fix (

    opened by eygraber 48
  • Handler doesn't execute Runnables when using Robolectric 3

    Handler doesn't execute Runnables when using Robolectric 3

    Handler for custom background thread (with looper) doesn't execute Runnables when used from inside test class. Looper created successfully for the thread.

    In test class, I'm waiting for async result via CountDownLatch.

    How can I fix that?

    Test class:

    @Config(constants = BuildConfig.class, sdk = 16)
    public class DispatchQueueTest
        public void testDispatch() throws InterruptedException
            DispatchQueue queue = new DispatchQueue();
            final CountDownLatch latch = new CountDownLatch(1);
            queue.dispatch(new Runnable()
                public void run()
            Assert.assertTrue("queue dispatch timeout", latch.await(1000, TimeUnit.MILLISECONDS));
        } // testDispatch

    Tested class:

    public class DispatchQueue implements Executor
        public static DispatchQueue main = new DispatchQueue(new Handler(Looper.getMainLooper()));
        private Handler handler;
        public DispatchQueue(Handler handler)
            this.handler = handler;
        public DispatchQueue()
            final CountDownLatch latch = new CountDownLatch(1);
            Thread thread = new Thread(new Runnable()
                public void run()
                    DispatchQueue.this.handler = new Handler();
                    //Logger.debug("DispatchQueue finished");
                latch.await(5, TimeUnit.SECONDS);
            catch(InterruptedException ex)
                Logger.error("Dispatch thread start failed.");
        } // DispatchQueue()
        public void close()
        public Handler getHandler()
            return handler;
        public void execute(Runnable runnable)
        public boolean dispatch(Runnable runnable)
            if(handler == null)
                return false;
        } // dispatch
        public Runnable dispatchAfter(long delayMs, Runnable runnable)
            if(handler == null)
                return runnable;
            handler.postDelayed(runnable, delayMs);
            return runnable;
        public void cancel(Runnable runnable)
            if(handler == null)
            if(runnable == null)
    } // DispatchQueue
    opened by virl 47
  • Init color array when decode for bitmap

    Init color array when decode for bitmap

    It will try to initialize ShadowBitmap.color when decode those source to try to fix

    It supports decodeByteArray, decodeFile, decodeResource, decodeStream, and decodeResourceStream.

    cla: yes 
    opened by utzcoz 42
  • Add example for custom shadow with Kotlin

    Add example for custom shadow with Kotlin


    The new module will be used for other Kotlin related compatibility integration tests too.

    opened by utzcoz 0
  • ClickableText offset value posted by compose rule test node click is different (end position) in 4.9.1 (and 4.9.2) than in 4.9 (start position)

    ClickableText offset value posted by compose rule test node click is different (end position) in 4.9.1 (and 4.9.2) than in 4.9 (start position)


    I have a test for some code in Jetpack compose, including a "" My ClickableText has its text attribute set to an AnnotatedString which consists of several parts. My test finds the relevant text (matches the first part of this AnnotatedString) and clicks on it. So I would expect the offset to be 0 (which it is in Robolectric 4.9). But in 4.9.1 / 4.9.2 the offset is instead "82", which happens to be the full length of the annotated string, so basically the end position of the string.

    Steps to Reproduce

    Prod code:

    fun TestComposable(onLinkClicked: (AnnotatedString.Range<String>) -> Unit) {
            modifier = Modifier,
            linkTextData = listOf(
                    tag = "not null",
                    annotation = "not null",
                    text = "License agreement",
                    onClick = onLinkClicked,
                LinkTextData(". "),
                    text = "Please review it and give your consent by checking the checkbox",
    private fun LinkText(modifier: Modifier = Modifier, linkTextData: List<LinkTextData>) {
        val annotatedString = createAnnotatedString(linkTextData)
            modifier = modifier,
            text = annotatedString,
            onClick = { offset ->
                   if (offset != 0) { 
                       throw IllegalStateException("Bug!")
    data class LinkTextData(
        val text: String,
        val tag: String? = null,
        val annotation: String? = null,
        val onClick: ((str: AnnotatedString.Range<String>) -> Unit)? = null,
    // This is a hack to be able to make part of a string clickable,
    private fun createAnnotatedString(data: List<LinkTextData>): AnnotatedString {
        return buildAnnotatedString {
            data.forEach { linkTextData ->
                if (linkTextData.tag != null && linkTextData.annotation != null) {
                        tag = linkTextData.tag,
                        annotation = linkTextData.annotation,
                        style = SpanStyle(
                            color = MaterialTheme.colorScheme.primary,
                            textDecoration = TextDecoration.Underline,
                    ) {
                } else {

    Test code:

    @Config(sdk = [Build.VERSION_CODES.S])
    class TestClass {
        val composeTestRule = createComposeRule()
        fun reproducible() {
            var onLinkClickedClicked = false
            composeTestRule.setContent {
                TestComposable(onLinkClicked = { onLinkClickedClicked = true })
            composeTestRule.onAllNodesWithText("License agreement", substring = true)
            composeTestRule.onNodeWithText("License agreement", substring = true)

    Robolectric & Android Version

    • Robolectric 4.9.1 / 4.9.2


    androidx-compose-compiler = "1.3.2"
    androidx-compose-material3 = "1.0.1"
    androidx-compose-ui = "1.3.2"
    androidx-compose-runtime = "1.3.2"
    androidxComposeCompiler = { module = "androidx.compose.compiler:compiler", version.ref = "androidx-compose-compiler" }
    androidxComposeRuntimeLivedata = { module = "androidx.compose.runtime:runtime-livedata", version.ref = "androidx-compose-runtime" }
    androidxComposeMaterialMaterial3 = { module = "androidx.compose.material3:material3", version.ref = "androidx-compose-material3" }
    androidxComposeUiTest = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx-compose-ui" }
    androidxComposeUiTooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "androidx-compose-ui" }
    androidxComposeTestManifest = { module = "androidx.compose.ui:ui-test-manifest", version.ref = "androidx-compose-ui" }

    Link to a public git repo demonstrating the problem:

    opened by alwa 14
  • RoboCookieManager supports override cookie has the same key

    RoboCookieManager supports override cookie has the same key


    The current implementation of RoboCookieManager only supports the host name and the key name of the Cookie. But it doesn't support path of the cookie. So this CL only compares the host name and the key name for the Cookie.


    opened by utzcoz 0
  • Unit tests 100x slower with Roboelectric (50ms to 3s)

    Unit tests 100x slower with Roboelectric (50ms to 3s)


    We have have many unit tests that depend on small parts of the SDK. The most common one being Uri.parse. We are currently static mocking those methods but it would be more robust to use Roboelectric.

    Unfortunately our testing has shown that the default Roboelectric test runner adds up to 3s of startup time to our tests.

    Most of our unit tests run in ~50ms without Roboelectric, but around 3s with it. Which makes it frustrating for quick test iterations.

    Is there an alternative test runner that would initialize less or do it lazily at least? (aka only pay for what you use). A good target would be 200ms startup time for tests only using Uri.parse or other static methods not using Activity or Context.

    Steps to Reproduce

    Run a test consisting of AssertNull(Uri.parse("")). Observe that it passes in 5ms. Run, with Roboelectric AssertNotNull(Uri.parse("")). Observe that it passes in 3s.

    Robolectric & Android Version

    Roboelectric 4.9, junit 4.13, android 33

    Link to a public git repo demonstrating the problem:

    Happy to create one if needed, but the default empty activity project in Android studio is enough to reproduce.

    opened by krocard 4
  • Updated an access modifier of an object decleration in

    Updated an access modifier of an object decleration in


    I spotted a todo comment that specified to not have the access specifier of the object classHandler (declaration) in line 23 as public. Therefore I resolved it by changing the access modifier to private. I hope this is valid (I'm new), thank you!

    Proposed Changes

    - public ClassHandler classHandler; // todo not public
    + private ClassHandler classHandler;
    opened by sandeshShahapur 3
  • robolectric-4.9.2(Dec 27, 2022)

    Robolectric 4.9.2 is a minor release that primarily fixes, which was an issue using native SQLite with older Linux machines.

    It also includes:

    • A fix for ShadowSpeechRecognizer in SDK <= 28 (0df34bf0cb5423afb64d7f4340c95e741ba26aa6, thanks @utzcoz)
    • Some fixes for instrumenting Jacoco-instrumented classes (7534d628fd69caab623b1ed31bf2096fd3c914db and 4e6047d88f7e8d9c83b13842a0d584d7eccd068a). Note there are still known issues with running Robolectric instrumentation on Jacoco-instrumented classes which should hopefully be fixed in 4.10.

    Full Changelog:

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.9.1(Dec 19, 2022)

    Robolectric 4.9.1 is a minor release that fixes several issues:

    • Fixes sdk levels in ShadowAppOpsManager (50e2cfa4294c5dcfb7127f51f355a366f947c89a, thanks @paulsowden)
    • Fixes an issue loading the native runtime on concurrent threads (0b4e996c27b85f05f7f52f75bc9d5109be7ef767)
    • Fixes some uses of LineBreaker and StaticLayout in Compose (ed2d7d3d600972090de29bcf9ad37d65a4d7ef47, thanks @samliu000)
    • Added proxy settings for fetching artifacts (bed3ca5a4ea314f730a9d58331b0099ca4c0abeb, thanks @sebastienrussell)
    • Avoid referring to Android S TelephonyCallback (d43ae9ad7b74512dbf89518247769ca5c2c4128c, thanks @styluo)
    • Fix data race in ShadowPausedLooper (cb231c8c133b6f2ed4e46148d1a4f551fdd52dd2)
    • Add shadow for LocaleManager#getSystemLocales (24d49f41227c35e0e3ce8564e404a39481c312e6, thanks @utzcoz)
    • Use uninterruptibly acquire for ResTable's lock (a221f6829110fd40b124527bde5317123f1737d9, thanks @utzcoz)
    • Update androidx.test dependencies to latest stable releases (0bdf89b884ac7c50c0e4d7a2b2fff848d795bf16, thanks @utzcoz)
    • Support zip files where EOCD's offset to central dir is -1 (9b36bc6b013db9e9eef5c509b2471cc8b0a7395a)

    Full Changelog:

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.9(Sep 30, 2022)

    Robolectric 4.9 adds support for Android T (API level 33).

    This release removes shadows supportv4 module fully.

    It also installs the Conscrypt as the primary Security provider. See for details.

    4.9 also turns on NATIVE sqlite mode by default for Mac and Linux. Windows will continue to use the LEGACY SQLite mode.

    What's Changed

    • Enable integration_tests:sparsearray tests by @utzcoz in
    • Enable CI when PRs are made to the 'google' branch by @hoisie in
    • Add triggerOnReadyForSpeech() to ShadowSpeechRecognizer.
    • Bump gradle-versions-plugin to 0.42.0 by @utzcoz in
    • Clean up tests.yml by @utzcoz in
    • Block UiController#loopMainThreadUntilIdle on registered idling resources being idle.
    • Return non-zero pointer from nCreateTextureLayer
    • Correctly register all idling resources
    • Update to declare Robolectric supports SDK 32 by @utzcoz in
    • Indicate windows are visible by default (flag enabled)
    • Add documentation to run tests on Emulator by @utzcoz in
    • Restore accidentally deleted link to building Robolectric
    • Ensure getNetworkCountryIso & getSimCountryIso return lowercase only, to match the actual APIs.
    • Update RoboLocationRequest equals() and toString().
    • Centralize the Injector logic to load the native runtime
    • Fixed PFD testGetFd_canRead test failed on macOS. by @ZSmallX in
    • Optimize CI a bit by @Goooler in
    • Clean up ctesque by @utzcoz in
    • Clean up by @utzcoz in
    • Bump Gradle to 7.4.2 by @utzcoz in
    • Remove unused Exception from example in by @utzcoz in
    • Error prone and google format fix annotation module by @hellosagar in
    • Update CI to use JDK 11.0.14 by @hoisie in
    • Support Canvas#drawRect with RectF by @Akshay2131 in
    • Remove maxSdk restrition for ShadowBiometricManager#canAuthenticate implementation by @utzcoz in
    • Switch to run tests on Emulator with SDK 29,32 by @utzcoz in
    • Support JDK 1.8 in ShadowWrangler invokespecial logic
    • build: bump errorprone plugin version from 1.3.0 to 2.0.2 by @hellosagar in
    • Bring integration_tests to API 32 by @utzcoz in
    • Add method expectLogMessagePatternWithThrowableMatcher to ExpectedLogMessagesRule so that users can check for a Throwable, as well as a log message pattern.
    • Add javadoc for DefaultShadowPicker by @hoisie in
    • Add SdkSuppress to some tests in ThemeTest and MotionEventTest by @hoisie in
    • Removed targetSdk from AndroidManifest.xml by @Umesh-01 in
    • Add getCurrentSyncs() in ShadowContentResolver by @Akshay2131 in
    • Make deep copy of mPointerProperties for NativeInput#copyFrom by @utzcoz in
    • Remove empty ShadowTextPaint by @utzcoz in
    • Migrate compileSdkVersion to compileSdk by @Akshay2131 in
    • Ensure ShadowActivity can work with project targetSdk less than S by @utzcoz in
    • Deprecate is___Intent methods of ShadowPendingIntent
    • Invoke the real View.draw(Canvas) from ShadowView.draw(Canvas)
    • Add looper mode assertions to ShadowChoreographer methods
    • Inline ShadowBitmapFactory#decodeByteArray by @utzcoz in
    • Skip to generate shadowOf for ShadowBackdropFrameRenderer by @utzcoz in
    • Add voice interactions support to ShadowVoiceInteractor
    • Bump guava to 31.1-jre by @utzcoz in
    • Improve the friendliness of code names for by @utzcoz in
    • Add shadows for createOnDeviceSpeechRecognizer and isOnDeviceRecognitionAvailable.
    • Deprecated Util#intArrayToList by @utzcoz in
    • Add Shadow implementation for ShadowApplicationPackageManager.getGroupOfPlatformPermission
    • Add support for changing NetworkSpecifier in NetworkCapabilities by @bacecek in
    • Migrate testRuntime to testRuntimeOnly by @utzcoz in
    • Add several new methods to ShadowPaint by @bacecek in
    • Fix non-determinism in ShadowContentResolverTest by @hoisie in
    • Tweak some tests in EspressoTest by @hoisie in
    • Remove deprecated ShadowPackageManager.getPackageInfoForTesting
    • Add baseline test cases for successfully expecting error and warn level logs using ExpectedLogMessagesRuleTest.
    • Implements methods isVoicemailNumber() and getVoicemailNumber() of ShadowTelecomManager.
    • Print log when skipping test because of legacy resource mode from P by @utzcoz in
    • Change the top level project name from parent to robolectric by @hellosagar in
    • Remove deprecated shadows/support-v4 by @utzcoz in
    • Use compat-target module to test compatibility from SDK 28 by @utzcoz in
    • [utils module] [Test conversion] Scheduler test by @hellosagar in
    • [utils module] [Test conversion] Pref stats collector test by @hellosagar in
    • [utils module] [Test conversion] Temp Directory test by @hellosagar in
    • [utils module] [Test conversion] Plugin finder test by @hellosagar in
    • [utils module] [Test conversion] Service finder adapter test by @hellosagar in
    • Extract auto-service version to by @utzcoz in
    • Removed NO_REBUILD option by @Umesh-01 in
    • Update ShadowView.setLayerType to call the real underlying implementation
    • Support test methods that have parameters
    • Use API level int for equality and hashing
    • Set Bitmap default density to qualifiers value
    • Replace Bouncycastle arrays with Java arrays by @akhilrm in
    • Use JDK 11 instead of 11.0.14 for CI by @utzcoz in
    • Prototype GMD configuration with plugin by @utzcoz in
    • Inline me inliner warning fix by @hellosagar in
    • [warning] Equals get class warning fix by @hellosagar in
    • [warning] Empty catch warning fix by @hellosagar in
    • [warning] Byte buffer backing array warning fix by @hellosagar in
    • Fix simulating window focus on android T.
    • [warning] Do not call suggester warning suppress by @hellosagar in
    • [Warning] Bad import warning fix by @hellosagar in
    • Migrate *SdkVersion to *Sdk by @utzcoz in
    • Migrate ActivityTestRule to ActivityScenario by @akhilrm in
    • Adds CameraInfo#canDisableShutterSound to the set of values returned from ShadowCamera#getCameraInfo().
    • [warning] InlineMeSuggester warning fix by @hellosagar in
    • Clean up ExpectedLogMessagesRuleTest by @utzcoz in
    • Fix code formatting for some SQLite tests by @utzcoz in
    • Run runConfigureICU with sh explicitly on Windows by @utzcoz in
    • Restructure androidx_test with sharedTest pattern by @utzcoz in
    • Bump Espresso to 3.5.0-alpha07 by @utzcoz in
    • chore: Set permissions for GitHub actions by @naveensrinivasan in
    • chore: Included githubactions in the dependabot config by @naveensrinivasan in
    • [warning] ThreadLocalUsage warning fix by @hellosagar in
    • [warning] StringSplitter warning fix by @hellosagar in
    • [warning] UnnecessaryParentheses warning fix by @hellosagar in
    • Add SuppressWarnings for a few NewApi warnings by @JuliaSullivanGoogle in
    • Add a test for TileService.requestListeningState
    • Implement UsbManager#openDevice and UsbManager#hasPermission(UsbAccessory)
    • Rollback of ShadowUsbRequest and ShadowUsbDeviceConnection
    • Implements ShadowUsbRequest and ShadowUsbDeviceConnection
    • Implement missing ShadowNativeSQLiteConnection.nativeClose
    • Add Bundle options to ShadowPendingIntent by @adaext in
    • Respect permissions granted by ShadowContextWrapper.grantPermissions() when sending broadcasts to receivers with permissions.
    • Conscrypt Testing - to run all of the tests on VMs by @Umesh-01 in
    • Avoid calling reflector as part of object finalization
    • Update ActivityScenario.launch() to remove BootstrapActivity
    • Rollback update ActivityScenario.launch() to remove BootstrapActivity
    • Remove '@Ignore' from EspressoTest by @hoisie in
    • Fix sharedTest pattern configuration for androidx_test by @utzcoz in
    • [warning] MissingSummary warning fix by @hellosagar in
    • [warning] InvalidInlineTag warning fix by @hellosagar in
    • Prepare to block explicit intents if they don't match intent filters on T+.
    • Retry connectedCheck on CI maximum three time by @utzcoz in
    • Add setSessionActiveState and getAllSessionCallbacks API to ShadowPackageInstaller.
    • Bump spotless to 6.9.1 by @utzcoz in
    • Fix ActivityNotFoundException in ActivityScenario in API 33
    • Redo update ActivityScenario.launch() to remove BootstrapActivity
    • Post call to recreate activity
    • Implement ShadowUiAutomation#setRotation
    • Add support for the onTopResumedActivityChanged in ActivityController
    • Make ResolveInfo generated by the shadow not crash on toString().
    • Add shadow method for VMRuntime.getNotifyNativeInterval
    • Add shadow methods for {g,s}etActiveDevice for BluetoothHeadset and BluetoothA2dp
    • Use the new getDeclaredField helper in more parts of ReflectionHelpers
    • Conscrypt as default Security Provider [Updated] by @Umesh-01 in
    • Idle main looper in AndroidX Fragment memory leak test
    • Added simulateSynthesizeToFileResult to support testing success, error and queued states.
    • Avoid calling the real DisplayManagerGlobal constructor in RNG
    • Store CallAudioState in FakeTelecomServer, instead of storing across various Shadow classes.
    • Change calls to Truth.assertThat(java.lang.Boolean) that ignore the result to call isTrue() on it instead.
    • Fix kotlinVersion typo by @utzcoz in
    • Implement ShadowBluetoothDevice#getBatteryLevel for O_MR1+
    • Make ValueCallbacks in RoboCookieManager nullable by @tinsukE in
    • [warning] UnusedMethod warning fix by @hellosagar in
    • [warning] UnnecessaryLambda warning fix by @hellosagar in
    • [warning] InvalidBlockTag warning fix by @hellosagar in
    • [warning] VariableNameSameAsType warning fix by @hellosagar in
    • Fix logspam in RobolectricTestRunnerMultiApiTest by @hoisie in
    • [warning] Catch and print stack trace warning fix by @hellosagar in
    • Reorder if statements in ShadowRegion.equals by @hoisie in
    • Remove unused test code by @hoisie in
    • Fix Javadoc for BackgroundTestRule by @hoisie in
    • [warning] DefaultCharset warning fix by @hellosagar in
    • [warning] Unused variable warning fix by @hellosagar in
    • [warning] JavaLangClash warning fix by @hellosagar in
    • [warning] EmptyBlockTag warning fix by @hellosagar in
    • Add support for FontFamily.getFont
    • GitHub Workflows security hardening by @sashashura in
    • [Warning] Eliminated AlmostJavadoc warnings across project by @hellosagar in
    • [warning] JavaUtilDate warning fix by @hellosagar in
    • Revert some method signature updates for Android T
    • Update Robolectric to be compiled against Android T by @hoisie in
    • Add support for two GNSS APIs to ShadowLocationManager.
    • Add test for RoboCookieManager#setCookie with null callback by @utzcoz in
    • [warning] RethrowReflectiveOperationExceptionAsLinkageError warning fix by @hellosagar in
    • Suppress RethrowReflectiveOperationExceptionAsLinkageError for Danger11Plus by @utzcoz in
    • Bump AGP to 7.2.2 by @utzcoz in
    • Add support for DevicePolicyManager in Android T
    • Parse idx and offset correctly from sparse resource entries
    • Deprecate and un-shadow ShadowScanResult class.
    • Bump AGP to 7.3 by @utzcoz in
    • Remove dead code that uses Plan based instrumentation (ClassHandler.Plan)
    • Run SDK 33 tests on CI by @utzcoz in
    • Bump maximum API for GMD to SDK 33 by @utzcoz in
    • Remove use-sdk from androidx_test/sharedTest/AndroidManifest.xml by @utzcoz in
    • [Warning] Eliminated AnnotateFormatMethod warnings by @hellosagar in
    • Remove 0x prefix for string format log by @utzcoz in
    • Bump compile/targetSdk to 33 by @utzcoz in
    • Remove unused Exception for ShadowActivityTest by @utzcoz in
    • Support Activity setShowWhenLocked() and setTurnScreenOn() by @utzcoz in
    • Exclude kotlin-stdlib dependency from utils generated .pom by @utzcoz in
    • Move dependencies of shadows/framework to by @utzcoz in
    • Bump ASM to 9.3 by @utzcoz in
    • Add the ability to deploy specific preinstrumented jars to maven by @hoisie in
    • Combine exceptions for ReflectionHelpers#getDeclaredField by @utzcoz in
    • Clean up ShadowAccountManager by @utzcoz in
    • Migrate Gradle dependencies to dependencies.gradle by @utzcoz in
    • Add alternative to Unsafe.defineAnonymousClass by @utzcoz in
    • Support all authentication results for BiometricManager by @charlesng in
    • Bump bcprov-jdk15on from 1.68 to 1.70 by @dependabot in
    • Bump constraintlayout from 2.1.3 to 2.1.4 by @dependabot in
    • Reuse bytecode of ClassWriter for ProxyMaker by @utzcoz in
    • Migrate instance calling in ReflectionHelpers to lambda by @utzcoz in
    • Bump compile-testing from 0.18 to 0.19 by @dependabot in
    • Bump apiCompatVersion from 4.7 to 4.8.2 by @dependabot in
    • Bump gson from 2.8.6 to 2.9.1 by @dependabot in
    • Bump core from 1.5.0 to 1.9.0 by @dependabot in

    New Contributors

    • @Goooler made their first contribution in
    • @hellosagar made their first contribution in
    • @Akshay2131 made their first contribution in
    • @Umesh-01 made their first contribution in
    • @bacecek made their first contribution in
    • @akhilrm made their first contribution in
    • @naveensrinivasan made their first contribution in
    • @adaext made their first contribution in
    • @tinsukE made their first contribution in
    • @sashashura made their first contribution in
    • @charlesng made their first contribution in
    • @dependabot made their first contribution in

    Full Changelog:

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.9-alpha-1(Sep 16, 2022)

  • robolectric-4.8.2(Aug 22, 2022)

    This is a minor release that fixes a number of issues, including:

    •, an issue closing SQLite databases.

    •, an initialization error in CountDownTimer.

    Use Robolectric 4.8.2:

    testCompile "org.robolectric:robolectric:4.8.2"
    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.8.1(May 3, 2022)

  • robolectric-4.8(Apr 28, 2022)

    Robolectric 4.8 adds support for Android S V2 (API level 32). It also contains many bug fixes and API enhancements.

    What's Changed

    • Turn off Gradle's fs watching during tests by @hoisie in
    • Remove unused resources.arsc file by @hoisie in
    • Fix name for macOS tasks to rename and upload binary files by @utzcoz in
    • Support overriding Icon loading executor from Icon#loadDrawableAsync. in
    • Update Android code search link to the public version in
    • Remove unnecessary TimePickerDialog constructor shadow in
    • Remove inaccessible Google issue tracker links in
    • Use Activity's member Instrumentation in ActivityController in
    • Fix UnsupportedOperationException if a leaked Activity.recreate is called in
    • Add ActivityController.close that transitions Activity to destroyed state in
    • Fix SDK version check for onPageFinished() call. It should be available for all SDK versions instead. See,%20java.lang.String) in
    • Limit instrumentation on interfaces in
    • Bump to version 3 of preinstrumented jars by @hoisie in
    • Migrate ShadowAccessibilityNodeInfo to reflector in
    • Add perf stat for applying styles in binary resources in
    • Refine methods: getYear(), getMonthOfYear(), getDayOfMonth() and getOnDateSetListenerCallback(). in
    • Add onConnectionEvent() to ShadowInCallService. in
    • Fix theme native object collection in Android S in
    • Use a self-hosted Mac M1 runner for the build_nativeruntime task by @hoisie in
    • Use 'processResources' task instead of 'jar' task for nativeruntime by @hoisie in
    • Remove unused Exception from test methods for dependency-on-stubs by @utzcoz in
    • Add solution log for unhandled PNG file by @utzcoz in
    • Remove instrumentedPackages workaround by @hoisie in
    • Remove unused org.robolectric.annotation.Config imports by @hoisie in
    • Only using AttributionSource for compile sdk 31 and above by @utzcoz in
    • Clear InputMethodManager.sInstance for SDK > P in
    • Adding VcnManagementService to ShadowSystemServices for VCN-related tests. in
    • Check Window flags when selecting root view in LocalUiController. #6741 in
    • Cleanup of AndroidManifest Activity references. in
    • Fix broken GitHub CI when running tests by @hoisie in
    • Fix some lint errors in Target29CompatibilityTest by @hoisie in
    • Avoid re-running ICU ./configure if Makefile exists by @hoisie in
    • Remove redundant SKIP_ICU_BUILD environment variable by @hoisie in
    • Remove unnecessary DatePickerDialog constructor shadow in
    • Add matrix computation support to ShadowRenderNode implementations in
    • Add support for building Robolectric's nativeruntime with gcc/g++ in
    • Switch to Ninja for building the native runtime in
    • Close android.database.Cursor objects in tests in
    • Fix remaining CloseGuard warnings in Robolectric tests in
      1. Adds ShadowVibrator#addSupportedPrimitives to enable in
    • Use real Android code for ContentProviderClient.release in
    • Update platformStrError to work in Windows in
    • Add setIsUniqueDeviceAttestationSupported and isUniqueDeviceAttestationSupported support to ShadowDevicePolicyManager in
    • Add custom JNI_INCLUDE_DIRS for Windows only by @utzcoz in
    • Use runner.arch when calculating ICU cache keys by @hoisie in
    • Add test ShadowPackageManagerTest#packageInstallerAndGetPackageInfo by @utzcoz in
    • fix for NPE when ShadowLegacyAssetManager is used by @kenyee in
    • Remove specific clang/clang++ env for build_native_runtime.yml by @utzcoz in
    • Support nativeruntime building for Windows by @utzcoz in
    • Handle more values in ShadowSystemProperties.getBoolean in
    • Update the windowConfiguration bounds when updating the display metrics in
    • Add shadows for UwbManager and RangingSession. in
    • Make two small improvements to ShadowMatrixTest in
    • Remove ServiceFinder in
    • Bump AGP to 7.1.0-beta05 by @utzcoz in
    • Bump SDK to 31 for integration_tests if possible by @utzcoz in
    • Remove explicit binary mode declaration for affected test modules by @utzcoz in
    • Remove specific clang/clang++ env for tests.yml by @utzcoz in
    • Creating ShadowVcnManager for vcn-related testing. in
    • Add READ_PHONE_STATE permission check to ShadowTelephonyManager.getVoiceNetworkType in
    • Update ShadowAppOpsManager to allow for multiple invocations of startWatching for a single listener. in
    • Add shadows for ImageReader and SurfaceTexture. Invoke updates from Surface to linked clients. in
    • Fix typo in
    • Add CI job to build nativeruntime for Windows by @utzcoz in
    • Intercept native Font states at Java level for Android S by @utzcoz in
    • Add regression test for mockito spy by @utzcoz in
    • Remove unused Exception from test methods for XmlResourceParserImplTest by @utzcoz in
    • Merge defaultConfig for ctesque build.gradle by @utzcoz in
    • Use guavaJREVersion from for some modules by @utzcoz in
    • Use version from for shadows:playservices by @utzcoz in
    • Call onSaveInstanceState after onStop from API P by @utzcoz in
    • Add perf stats for loading plugins and loading the native runtime in
    • Add two S-specific test cases for ShadowDevicePolicyManager in
    • Fix class description. in
    • Support NotificationManager.addAutomaticZenRule that could add AutomaticZenRule without owner,but has configurationActivity. in
    • Add plumbing for source resource id getter in
    • Add ShadowConnection that records the last event sent through Connection.sendConnectionEvent. in
    • Bump AGP to 7.1.0-rc01 by @utzcoz in
    • Remove unused exception from tests for SQLiteLibraryLoaderTest by @utzcoz in
    • Clean up androidx_test by @utzcoz in
    • set createdFromBytes also when using decodeByteArray with options by @edwinvanderham in
    • Move ShadowWranglerIntegrationTest.ShadowFooParent to sandbox testing package in
    • Use invokespecial when invoking shadow constructors in
    • Add a ShadowCloseGuard and CloseGuardRule for verifying all CloseGuards have been closed in
    • Trigger listeners for ServiceState in TelephonyManager.listen in
    • Tweak precondition check in NotificationManager.updateAutomaticZenRule by @hoisie in
    • Makes sparse array implement the set() method for all api levels by adding the byte code for it in the ClassInstrumentor. by @JuliaSullivanGoogle in
    • Intercept the getInt$() and setInt$(int) functions on FileDescriptor by @hoisie in
    • Simplify SparseArray.set instrumentation by @hoisie in
    • Retain outer class assignment in the constructor in
    • Add FileDescriptor transform to ShadowMediaMetadataRetriever. in
    • Add shadow method for WifiManager.isStaApConcurrencySupported in
    • Update ShadowVcnManager to support VcnConfig setting and subscription group (ParcelUuid) setting. in
    • Fix signature for ShadowPausedMessageQueue 'enqueueMessage' reflector in
    • Allows calling clearVcnConfig() when the vcnConfig being cleared is not set. in
    • Enable realistic View matrix calculations by default in
    • Add unregisterStats(path) method in ShadowStatsFs in
    • Bump icu4j to 70.1 by @utzcoz in
    • Bump apiCompatVersion to 4.7 by @utzcoz in
    • Bump AGP to 7.1.0 by @utzcoz in
    • Added JDK prerequisites in README, for contributors to build project. by @ZSmallX in
    • Remove deprecated supportv4 shadows by @utzcoz in
    • Change ShadowAppWidgetManager to use AppWidgetHostView instead of FrameLayout to support ListView / remote collections testing. in
    • Reformat AndroidInterceptors in
    • Add shadow for SurfaceControl#nativeCreate in
    • Changes ShadowActivity to use reflector instead of using direct reflection to call certain methods by @JuliaSullivanGoogle in
    • Add a test case for spying on a shadowed object in
    • Trigger an asynchronous broadcast of scan results in WifiManager.startScan in
      1. Stores VibrationAttributes in ShadowVibrator and exposes a getter getVibrationAttributesFromLastVibration to get VibrationAttributes for the last vibration. in
    • Make loading the native runtime extensible in
    • Return null for external files directory if external storage is unavailable in
    • Fix touch event dispatch to not go to out of bounds non touch modal windows in
    • Add getShareTitle() and getShareDescription() to ShadowBugreportManager, set in
    • Add shadow for CompanionDeviceManager in
    • Add support for new S ProviderProperties APIs. in
    • Make deprecation comment in RuntimeEnvironment.application refer to RuntimeEnvironment.getApplication() instead of in
    • Added register/unregister callback shadows for CameraManager. in
    • Return Number from ShadowSurfaceControl#nativeCreate to support sdk 18/19 in
    • Fix some lint warnings in
    • Change ShadowBluetoothAdapter to cache getRemoteDevice instances. In android, the state for a given device (uniquely identified by its address) is global. When you have two instances of BluetoothDevice and mutate one, the other will reflect it, even though they are not the same java object. in
    • Add support for touch mode in
    • Return Number from ShadowSurfaceControl#nativeCreate to support sdk 18/19 by @JuliaSullivanGoogle in
    • Added more prerequisites for robolectic building and testing in README by @ZSmallX in
    • Added junit dependency in README. by @ZSmallX in
    • Migrate AndroidJUnit4 to ext version for ctesque by @utzcoz in
    • Add a task to fetch nativeruntime artifacts from a GitHub CI run by @hoisie in
    • Add integration tests for mokito-kotlin's regression by @ZSmallX in
    • Remove ShadowsPlugin from supportv4/build.gradle by @hoisie in
    • Bump massive dependencies for androidx and androidx_test by @utzcoz in
    • Optimizes getFd and close behaviors for ParcelFileDescriptor by @ZSmallX in
    • Add support for Build.setSerial in ShadowBuild in
    • Add DragEventBuilder helper in
    • Flesh out support for GNSS APIs. in
    • Reduce visibility of ShadowActivity.isFinishing in
    • create ShadowActivity#simulateGetDirectActions for testing assistant requesting DirectAction from an Activity in
    • Add shadow implementations for source resource id getters in
    • Adds a Robolectric property to allow users to build Robolectric without the preinstrumented jars to allow for better testing of new features. in
    • Adds shadow for DisplayHashManager. in
    • Remove enableMatrix=true properties, default is now true in
    • Add interceptor for Reference.refersTo. in
    • Speed up ShadowRcsUceAdapterSTest. in
    • Run google-java-format on ShadowMatrixTest in
    • Make ShadowPackageManager generatePackageInfo extensible. in
    • Removing the onStatusChanged() invoke when VcnStatusCallback is registered. in
    • Sets github's test gradle usePreinstrumentedJars value to false by default. in
    • Add ShadowWindowManagerGlobal#getLastDragClipData method in
    • Update SQLiteConnection shadows to support Android T changes in
    • Update ShadowActivityThread for T in
    • Add T-specific logic for ActivityController.windowFocusChanged in
    • Prepare to adjust for changed BluetoothAdapter.setScanMode signature. in
    • Return the original method's test name in
    • Support new API registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags) after O in
    • Add shadows for Settings.Secure.getIntForUser. in
    • ShadowImageReaderTest: Move Config setting to class level since its common for all tests. in
    • Pass through openInputStream calls if a provider for the authority is registered. in
    • Fix for potential race condition in ShadowMediaCodec async mode. in
    • Enable WebView.createWebMessageChannel shadow. in
    • Bump the runtime SDK of shadows:httpclient tests to S in
    • Add new VibrationAttributesBuilder in
    • Add support for new constructor in StorageVolumeBuilder in
    • Create new RangingSessionBuilder in
    • Mimic actual MediaCodec creation logic. in
    • Add unregisterSessionCallback implementation in the PackageInstaller. in
    • Make the ShadowPausedSystemClock thread safe in
    • Add support for new field in DisplayManager BrightnessConfiguration APIs in
    • Make TestParcelable* classes public in
    • Add getThermalStatusListeners() to return registered listener for shadow power manager. in
    • Add USB signaling API override support to ShadowDevicePolicyManager in
    • Remove robolectric.rendernode.enableMatrix flag in
    • Update check_java_formatting action to use Google Java Format 1.15 by @hoisie in
    • Open LocationRequest methods up down to Kitkat when they were first added. in
    • Add getTotalSize, setTotalSize, getBytesSoFar and setBytesSoFar for DownloadManager.Request in ShadowDownloadManager. in
    • Add nCreateTextureLayer to ShadowHardwareRenderer in
    • Add some concurrency tests for ShadowPausedSystemClockTest in
    • Add a test for ActivityNotFoundExceptions in Espresso intents by @hoisie in
    • Add support for getInstallSourceInfo in ShadowPackageManager. The behaviour is independent of existing getInstallerPackage support. in
    • Apply style/lint fixes to mockito-kotlin test code by @hoisie in
    • Use ktfmt to format kotlin code by @utzcoz in
    • Skip ShadowSQLiteConnection test on M1 by @utzcoz in
    • Update minimum requirement toolchain version by @utzcoz in
    • Add implementation for shadows of AccessibilityManagers StateChangeListener by @MichaelEvans in
    • Fix format problem of ShadowAccessibilityManager by @utzcoz in
    • Have ShadowApplicationPackageManager#getPackageArchiveInfo call super() when apiLevel >= T in
    • Fix setTouchExplorationEnabled() not calling onTouchExplorationStateChanged() on the TouchExplorationStateChangeListeners in
    • Adding an overload method to registerReceiver to include flags when registering a receiver with a broadcast permission in
    • Fix bitmap mutable, premutliplied, and alpha properties. in
    • Add @Implementation where missing in Robolectric's shadows in
    • Run google-java-format on ShadowTime in
    • Add support for ColorSpace to ShadowBitmap in
    • Add support for Android S V2 in Robolectric by @hoisie in
    • Add a "default" list of system features to ShadowPackageManager in
    • Update ShadowBluetoothDevice to throw an exception if the BLUETOOTH_CONNECT permission isn't granted. in
    • Don't decode image bytes as utf-8 encoded string in
    • Improve support for low-power idle modes in ShaddowAlarmManager in
    • Add support for shadowing TaskInfo#isVisible. in
    • Migrate from strongly discouraged @Test(expected = ...) to assertThrows(...). in
    • Adding ShadowContentCaptureManager to Q+ in
    • Add support for save/restore in ShadowCanvas in
    • Fix TouchExplorationStateChangeListener trigger logic for SDK < O in
    • Migrate ShadowTaskInfo to a builder in
    • Bump preinstrumented jars to version 4 by @hoisie in
    • Re-enable nativeruntime building for Windows by @hoisie in
    • Disable shadowOf generation for DisplayHashManager by @hoisie in
    • Enable integration_tests:sparsearray tests by @utzcoz in
    • Enable CI when PRs are made to the 'google' branch by @hoisie in
    • Add triggerOnReadyForSpeech() to ShadowSpeechRecognizer. in
    • Bump gradle-versions-plugin to 0.42.0 by @utzcoz in
    • Clean up tests.yml by @utzcoz in
    • Block UiController#loopMainThreadUntilIdle on registered idling resources being idle. in
    • Return non-zero pointer from nCreateTextureLayer in
    • Correctly register all idling resources in
    • Update to declare Robolectric supports SDK 32 by @utzcoz in
    • Indicate windows are visible by default (flag enabled) in
    • Add documentation to run tests on Emulator by @utzcoz in
    • Restore accidentally deleted link to building Robolectric in
    • Ensure getNetworkCountryIso & getSimCountryIso return lowercase only, to match the actual APIs. in
    • Update RoboLocationRequest equals() and toString(). in
    • Centralize the Injector logic to load the native runtime in
    • Fixed PFD testGetFd_canRead test failed on macOS. by @ZSmallX in
    • Optimize CI a bit by @Goooler in
    • Clean up ctesque by @utzcoz in
    • Clean up by @utzcoz in
    • Bump Gradle to 7.4.2 by @utzcoz in
    • Remove unused Exception from example in by @utzcoz in
    • Error prone and google format fix annotation module by @hellosagar in
    • Update CI to use JDK 11.0.14 by @hoisie in
    • Support Canvas#drawRect with RectF by @Akshay2131 in
    • Remove maxSdk restrition for ShadowBiometricManager#canAuthenticate implementation by @utzcoz in
    • Switch to run tests on Emulator with SDK 29,32 by @utzcoz in
    • Support JDK 1.8 in ShadowWrangler invokespecial logic in
    • build: bump errorprone plugin version from 1.3.0 to 2.0.2 by @hellosagar in
    • Bring integration_tests to API 32 by @utzcoz in
    • Add method expectLogMessagePatternWithThrowableMatcher to ExpectedLogMessagesRule so that users can check for a Throwable, as well as a log message pattern. in
    • Add javadoc for DefaultShadowPicker by @hoisie in
    • Add SdkSuppress to some tests in ThemeTest and MotionEventTest by @hoisie in
    • Removed targetSdk from AndroidManifest.xml by @Umesh-01 in
    • Add getCurrentSyncs() in ShadowContentResolver by @Akshay2131 in
    • Make deep copy of mPointerProperties for NativeInput#copyFrom by @utzcoz in
    • Remove empty ShadowTextPaint by @utzcoz in
    • Migrate compileSdkVersion to compileSdk by @Akshay2131 in
    • Ensure ShadowActivity can work with project targetSdk less than S by @utzcoz in

    New Contributors

    • @kenyee made their first contribution in
    • @edwinvanderham made their first contribution in
    • @JuliaSullivanGoogle made their first contribution in
    • @ZSmallX made their first contribution in
    • @MichaelEvans made their first contribution in
    • @Goooler made their first contribution in
    • @hellosagar made their first contribution in
    • @Akshay2131 made their first contribution in
    • @Umesh-01 made their first contribution in

    Full Changelog:

    Use Robolectric:

    testCompile "org.robolectric:robolectric:4.8"
    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.8-alpha-1(Mar 21, 2022)

  • robolectric-4.7.3(Dec 1, 2021)

    This is a minor release that fixes #6883, a NoClassDefError that can occur if the compileSdk < 31. Thanks for @ninniuz for reporting and @utzcoz for the fix (#6884).

    It also fixes a minor case of test pollution, where a single Activity could leak across tests (see 5a1f02aaf37f425f8938ae41df5d7aa1b72bba9c for details).

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.7.2(Nov 20, 2021)

    This is a minor release that fixes a memory leak of Theme objects in binary resources for Android S (#6872). Thanks @calvarez-ov for the report and helping debug.

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.7.1(Nov 18, 2021)

    This is a minor release that fixes #6858. In that issue, certain Android classes could not be mocked by Mockito due to some changes to Robolectric instrumentation performed on interfaces.

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.7(Nov 12, 2021)

    Robolectric 4.7 adds support for Android S (API level 31).

    Another big feature is support for Apple Silicon (Mac M1). Robolectric 4.7 now contains its own native implementation of the android.database.sqlite package. For Mac M1 machines, this SQLite mode is the default. For other OS's and architecture, use @SQLiteMode(NATIVE) to enable it. This new mode is currently only available for Mac and Linux. Native SQLite should be significantly faster, around 50-90% faster for SQLite operations, than the LEGACY SQLite mode. There were also several other performance improvements made for SQLite operations -- #6687, #6690, and #6711 (thanks @al-broco!).

    The support v4 shadows are also deprecated at this release, and they will be removed at Robolectric 4.8.

    Robolectric 4.7 also supports JDK 17.

    What's Changed

    • Clear cookies after test finished for CookieManagerTest by @utzcoz in
    • Only using ApplicationExitInfo for compile sdk 30 and above by @utzcoz in
    • Rebase PR 4064 - Fix NPE during saving state of WebView by @utzcoz in
    • Converting the String version of directlyOn(...) to @Direct with reflector(...). by @hoisie in
    • Add ITelephonyRegistry to ShadowServiceManager
    • Implement new #startActivity methods for ShadowCrossProfileApps.
    • Add ShadowMediaExtractor.
    • Converting onVsync calls from ReflectionHelpers to use @Direct with reflector(...) instead.
    • Update ShadowDisplayEventReceiver to support S
    • Converting the proxy version of directlyOn(...) to @Direct with reflector(...). by @hoisie in
    • Fix Robolectric camera shadows to work with newer SDK versions.
    • Converting recycleUnchecked calls to use @Direct with reflector(...) in place of ReflectionHelpers.
    • Cleaning up unnecessary @Direct annotations in DirectActivityReflector.
    • Fixing the incorrect method signature in AssetManagerReflector that breaks GitHub CI.
    • No longer automatically log everything in ShadowLog if stream is specified
    • Support IntBuffer with copyPixelsFromBuffer
    • Suppress missing /system/etc/fonts.xml log noise for SDK 27
    • Add perf stats for reflector class definition
    • Use Object to replace GnssAntennaInfo.Listener at ShadowLocationManager by @utzcoz in
    • Trimming the localrepository string. by @Squadella in
    • Merging the the separate Reflector interfaces for Message into one main interface.
    • Remove OldClassInstrumentor
    • Remove unnecessary ShadowLegacyMessage.isInUse
    • Converting directlyOn(...) to @Direct with reflector(...) in ShadowWindow and ShadowPhoneWindow.
    • Intercept calls to methods in {@link Socket} not present in the OpenJDK.
    • Use bulk operations in copyPixels{to,from}Buffer
    • Improve reflector caching using a regular HashMap
    • Add shadow method ShadowLauncherApps#getShortcutConfigActivityList.
    • Add OnPermissionChangedListener implementation to ShadowPackageManager.
    • Update minSdkVersion to 14 in some integration_test manifests
    • Merge InvokeDynamicClassInstrumentor into ClassInstrumentor
    • Add a shadow method for PackageManager#getText which gets a String associated with package name and resource id.
    • Pass through openInputStream calls for SCHEME_ANDROID_RESOURCE
    • Names thread used by ShadowFileObserver to match behavior of FileObserver.
    • Migrate from AnnotationValue#toString to auto-common's AnnotationValues.toString.
    • Fix fidelity issue with Cursor.getBlob on a String column
    • Remove InvokeDynamic perf stats
    • Fix SQLiteDatabaseTest foreign key test to match Android behavior
    • Add cardId support for ShadowEuiccManager.
    • Add OnUidImportanceListener implementation to ShadowActivityManager and SCREEN_ON/SCREEN_OFF broadcasts to ShadowPowerManager.
    • Instrument default interface methods
    • Support Object array and Iterable as return type for single parameter by @utzcoz in
    • Rebase PR 6265: Bounds check the correct variable. by @utzcoz in
    • Remove allocation in ShadowCursorWindow.Data init by @al-broco in
    • internal
    • Add perfstats for ShadowSQLiteConnection
    • Add support for startWatchingMode() with flags.
    • Make isOpActive() public, so it can be used in tests below Android R.
    • Add a sqlite test using LIKE ? ESCAPE ?
    • Throw an exception if a query is performed using SQLiteDatabase.execSQL
    • Add isAutoRevokeWhitelisted implementation to ShadowPackageManager.
    • Add support for setting smart replies on ShadowRanking object, so getSmartRanking method can be used in tests.
    • Use full class name in the SQLiteConnection shadow
    • Improve NFC testability:
    • Add experimental sqlite shadows derived from AOSP SQLite
    • Exclude built-in config from being reloaded in Configuration registry
    • Make legacy ShadowSQLiteConnection implementation methods protected
    • Newly added shadow class for MediaStore is exposed to open source rebolectric library
    • Update ShadowAppWidgetManager to better handle RemoteViews with multiple layouts
    • Add shadow functionality for removing bonds(systemAPi)
    • Add support for NetworkInfo.extraInfo to ShadowNetworkInfo
    • Update default SQLite synchronous and journal modes
    • Add a null check to ShadowCursorWindow.put{Blob,String}
    • Add parameterized test name method to the test runner
    • Add ability to uninstall app widgets to
    • Add ShadowInetAddressUtil class
    • Add @InlineMe to deprecated ShadowLooper APIs.
    • Add @InlineMe to deprecated, inlineable APIs.
    • Add setAnchor to ShadowAccessibilityWindowInfo
    • Fix an ArrayIndexOutOfBoundsException in ByteBucketArray
    • Add missing implementation for __android_log_assert
    • Remove mocking from FragmentControllerTest
    • Add API to retrieve Intent used to start SpeechRecognizer
    • Update default SQLite synchronous mode when WAL is enabled
    • Fix formatting in ShadowSQLiteConnectionsTest
    • Add a SQLite mode that enables the new native Android SQLite shadows
    • Use offset from BufferInfo instead of ByteBuffer for ShadowMediaMuxer#writeSampleData by @utzcoz in
    • Support to open fd for uncompressed file in asset by @utzcoz in
    • Update gradle wrapper to 7.2 by @utzcoz in
    • Improve resetter for NfcAdapter and CardEmulation by @utzcoz in
    • Remove debug print statement
    • Fixes WindowInfo children not cloned in ShadowAccessibilityWindowInfo
    • Clarify ShadowLooper.idle message when test fails.
    • Skip ErrorProne on GitHub CI runs
    • Migrate off deprecated mockito APIs
    • Remove CircleCI metadata
    • Fix ShadowMediaPlayer#prepare() to invoke prepared listener on handler instead of executing directly on calling thread.
    • Delete ShadowBaseLooper
    • Include stack trace in System.log[WE] calls.
    • Implemented startForeground(int, Notification, int).
    • Fix spurious CloseGuard errors in Surface and SurfaceControl
    • Specify LEGACY SQLite mode for ShadowSQLiteConnectionTest
    • Add CMake build for SQLite native artifacts by @hoisie in
    • Deprecate ShadowSwipeRefreshLayout. by @utzcoz in
    • Add CI job to check aggregateDocs by @utzcoz in
    • Deprecate the supportv4 shadows as mentioned in #6185 by @alsutton in
    • Rework api classification and enforcement.
    • Add toString to ShadowApplication.Wrapper
    • Use more conventional name for the native runtime library
    • Add setWifiApConfiguration & getWifiApConfiguration to ShadowWifiManager
    • Make IntentsTest work on device without browser.
    • Merging HardwareRendererCompat fixes into one branch by @dmeng in
    • Don't use HARDWARE bitmaps in Bitmap#createBitmap.
    • Fix missing imports when building on Mac OSX.
    • Update ShadowInCallService so that onCallAudioStateChanged callback is invoked when the audio route is changed.
    • Reduce usage for this$0 by @utzcoz in
    • Update nativeruntime CMake build to support Mac M1 by @hoisie in
    • Use the display ID in the provided ActivityOptions when launching activities, instead of always using the default display.
    • Add ctesque common tests to androidTest by @utzcoz in
    • Create a separate task to prefetch non-instrumented SDKs by @hoisie in
    • Clarify error message if the SQLite submodule is missing by @hoisie in
    • Make implementation classes protected on ShadowRenderNode by @hoisie in
    • Support self notification callbacks for AppOpsManager
    • Add a ShadowPackageBackwardCompatibility class to handle when multiple APIs are on the classpath
    • Always look for tzdata in the corresponding android-all jar instead of the classpath
    • Fix NPE when calling Path.arcTo with an invalid arc
    • Add support to system flags on ShadowWindow
    • Synchronize BinderService.getBinder
    • Add a binder service for TELEPHONY_SERVICE in ShadowServiceManager.
    • Add support for Android S
    • Add a test for getting and setting the global animation duration
    • Add supports of addOnActiveSessionsChangedListener with 3-arguments for ShadowMediaSessionManager.
    • Bump AGP to 7.1.0-beta02 by @utzcoz in
    • Default to native Android SQLite on the Mac M1
    • Update ShadowRenderNodeAnimator to direct reflector
    • Turn off shadowOf generation for RoleControllerManager
    • Deprecate the proxy version of directlyOn
    • Update ShadowApplicationPackageManager.getPackageArchiveInfo to use reflector
    • Migrate supportv4 shadows from directlyOn proxy to reflector
    • Ensure that ShadowAccessibilityRecord fields are preserved during AccessibilityEvent copy.
    • Migrate to use platform InstrumentationRegistry for LocalActivityInvoker by @utzcoz in
    • Use direct reflector for AcccessibiltyRecord.init in
    • Add ShadowTimePickerDialog.getIs24HourView in
    • Add libicu as a git submodule by @hoisie in
    • Disable the universal library for Mac OS by @hoisie in
    • Bump asm to 9.2 by @utzcoz in
    • Add workflow that builds native runtime and uploads artifacts by @hoisie in

    New Contributors

    • @Squadella made their first contribution in
    • @al-broco made their first contribution in
    • @dmeng made their first contribution in

    Full Changelog:

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.7-alpha-2(Nov 8, 2021)

  • robolectric-4.7-alpha-1(Nov 5, 2021)

  • robolectric-4.6.1(Jul 4, 2021)

    This is a minor release that fixes #6589, in which ShadowActivityManager contained a reference to, introduced in SDK 30, in public method. This caused shadowOf to fail if the target SDK was < 30. Thanks to @utzcoz for the fix and @jankowskib for reporting the issue.

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.6(Jul 2, 2021)

    Robolectric 4.6

    The highlights of this release are:

    • Uses preinstrumented jars by default, significantly decreasing startup time.
    • Massive fidelity improvements for Bitmap and BitmapFactory.
    • Tons of bug fixes and fidelity improvements.

    What's Changed

    • Add ShadowMagnificationController for N+ in
    • Add ShadowSoftKeyboardController for N+ in
    • Move debug class dump logic from ClassInstrumentor to SandboxClassLoader in
    • Tweak ShadowTextToSpeech OnInitListener API in
    • Lay the groundwork to use preinstrumented android-all jars in Robolectric. in
    • Platform compatibility enhancements in
    • Upgrade google-java-format to 1.9 by @utzcoz in
    • Added gradle dependency version checker to the build by @alsutton in
    • Update android support libraries to v28.0.0 by @alsutton in
    • Synchronize Truth version being used to be v1.1.2 by @alsutton in
    • ShadowInCallService and ShadowPhone offer a method addCall() which adds a call in
    • Deprecate RoboExecutorService. in
    • Revert some recently added native method logic in ClassInstrumentor in
    • Remove debug print statements from AndroidInterceptors in
    • Consistently use reflection for accessing the "DURATIONS" array. in
    • Deprecate TextLayoutMode. in
    • Remove use of deprecated and redundant TextLayoutMode.REALISTIC,as its now the default behavior. in
    • Fix deleting temp directories in
    • Call ShadowBackupManager's getAvailableRestoreToken instead of framework's one as we already have implementation of that method in the shadow under the method: getPackageRestoreToken() in
    • Add Support for startAsyncSection and endAsyncSection to ShadowTrace in
    • Move AndroidConfigurer and AndroidInterceptors to sandbox project in
    • Add visibility to ShadowTrace.AsyncTraceSection in
    • Disable instrumenting AndroidX classes by default in
    • Migrate CI checks from CircleCI to GitHub actions by @LitterSun in
    • Fix typo and run tests on SDK 30 by @hoisie in
    • Remove publish_test_results job by @hoisie in
    • Fix some errorprone warnings by @utzcoz in
    • Create a new ShadowFileObserver that implements (some of) FileObserver functionality for Robolectric in
    • Make ShadowPackageManager.getPackageArchiveInfo extendable in
    • Add a method to StreamConfigurationMapBuilder shadow class to support cameraX testing. in
    • platform support in
    • Shadow tone generator that implements a static state tracking mechanism for all played tones in
    • update robolectric build.gradles to use latest androidx.test artifacts in
    • Update ShadowBugreportManager with additional functionality: in
    • Move overriding PolicyManager.makeNewWindow to ShadowPolicyManager in
    • Add opt-in lazy loading of application+instrumentation in Robolectric in
    • [LazyLoad] Explicitly make method config default to class config, and class config default to package config in
    • Check framework jar path before calling AssetManager from ShadowResources in
    • Add check to AndroidTestEnvironment.installAndCreateApplication to ensure that it is only called from the main thread in
    • Fix syntax warning of build.gradle by @utzcoz in
    • Restore JarInstrumentor in
    • Clean up test code under shadows by @utzcoz in
    • make ShadowContentResolver lazy load friendly in
    • Make ShadowApplication.getInstance call RE.getApplication. in
    • Switch to using preinstrumented android-all jars by default in
    • Fix MavenDependencyResolverTest in restricted test environments in
    • Move wakelock and dialog recording storage from ShadowApplication to their respective shadows. in
    • Add setCounter functionality to ShadowTrace in
    • Remove maxSdk=R config from test code in
    • Ensure Bitmap.Config is set on the output after Bitmap.createBitmap in
    • Robolectric ShadowCall: Adds hasSentRttRequest and hasRespondedToRttRequest functionality to the shadow. in
    • Ensure Bitmap.Config is set on the output after Bitmap.createScaledBitmap in
    • Slightly improve the fidelity of comparing scaled bitmaps in
    • Add implementation for packageManager.getPermissionFlags and packageManager.updatePermissionFlags in
    • Always return the result of BitmapFactory.finishDecode for SDK < 19 in
    • Make RuntimeEnvironment.getActivityThread and ShadowDisplayManagerGlobal lazy load friendly in
    • Move call to getApplicationContext() outside the runnable so that we don't try to load the application from a separate thread when lazy loading in
    • Explicitly instantiate the application for the stub tests where we will assert on app state in
    • Add support for setting-getting RatingType in ShadowMediaController in
    • Create a shadow implementation of NotificationListenerService. in
    • Add showSession to ShadowVoiceInteractionService in
    • Init color array when decode for bitmap by @utzcoz in
    • Init color array for decode file descriptor by @utzcoz in
    • Migrate to preferred BugCheckerRefactoringTestHelper.newInstance overload in
    • Propagate Bitmap.Options.isMutable to bitmap in
    • Make dataChangeCount part of BackupManagerServiceState. in
    • Upgrade ErrorProne and fix ErrorProne related build errors in
    • Update FrameMetricsBuilder to explicitly set TOTAL_DURATION in
    • Execute directly on CI machines in
    • Clear ShadowBitmap description when eraseColor is called in
    • Make Activity.getCallingPackage() and Activity.getCallingActivity() consistent. in
    • Add basic implementation of Canvas.drawRect(Rect, Paint) in
    • Improve the fidelity Canvas.drawBitmap(Bitmap, float, float, Paint) in
    • Improve fidelity of ImageView.draw(Canvas) in
    • Fix ShadowBitmapFactoryTest in non-Gradle environments by @hoisie in
    • Keep ubuntu to ubuntu-18.04 on CI by @utzcoz in
    • add test around ShadowDisplayManagerGlobal.getInstance in
    • Use bulk api to set pixels by @utzcoz in
    • Set lastAbandonedAudioFocusListener for AudioManager.abandonAudioFocusRequest and set OnAudioFocusChangeListener in AudioFocusRequest constructor. in
    • Add ShadowBugreportManager.requestBugreport(). in
    • Add implementation for getInstalledProvidersForPackage() to ShadowAppWidgetManager in
    • Fix several NPEs in ShadowXMLBlock in
    • Update ShadowLocationManager with intent broadcast behavior. in
    • Always load application at start of RuntimeEnvironment.setQualifiers in
    • Add a width and height check in Bitmap.createScaledBitmap in
    • Directly use FrameMetrics.SWAP_BUFFERS_DURATION for the value of TOTAL_DURATION in
    • Implement getPackagesForOps methods for ShadowAppOpsManager. by @hoisie in
    • Add check for stride when calling bulk ShadowBitmap.getPixels in
    • Make the Bitmap returned by Bitmap.createScaledBitmap mutable in
    • Significantly improve the performance of BitmapFactory.decode* operations in
    • Deprecate all public ShadowBitmapFactory methods in
    • Remove the main thread check in installAndCreateApplication, as we don't see any problems when tests create from a background thread in
    • Added missing overload for ShadowInstrumentation.execStartActivity. in
    • Add ShadowPowerManager#setAdaptivePowerSaveEnabled. in
    • Populate streamType and durationHint for AudioFocusRequest. in
    • Add setUserRestriction() for ShadowUserManager in
    • Return null from the old API for getPackagesForOps, to match it to what the real API does. in
    • Add ShadowActivityThread.setCompatConfiguration to use instead of in
    • Add option to not allow invalid image data in BitmapFactory.decode methods in
    • Add the following to ShadowActivityThread in
    • Add method that consumes and returns all service Intents. in
    • Add mutable checking for ShadowBitmap.setPixels by @utzcoz in
    • Add ShadowSensorManager#removeSensor by @utzcoz in
    • Make RobolectricTestRunner#getConfiguration private by @utzcoz in
    • Update ShadowBitmap to be backed by Java's BufferedImage in
    • Use master thread scheduler to control legacy system clock directly, instead of going through ShadowApplication in
    • Rename LazyLoadApplication to LazyApplication and update all references accordingly in
    • Add a global view action listener system to ShadowView for the performClick() and performLongClick() functions. in
    • fix one more LazyLoadApplication -> LazyApplication in
    • Add test case for getting the outer object using reflector in
    • Remove CachedDependencyResolver and CachedMavenDependencyResolver in
    • Migrate jcenter to mavenCentral by @utzcoz in
    • Change max sdk to R for ShadowIntrumentation#execStartActivityAsCaller by @utzcoz in
    • Revert "Change max sdk to R for ShadowIntrumentation#execStartActivityAsCaller" by @hoisie in
    • Udpate gradle dependencies by @utzcoz in
    • Adds triggerOnEndOfSpeech to ShadowSpeechRecognizer. in
    • Add deprecated tags to methods in SupportFragmentTestUtil. in
    • Update ShadowLocationManager with R APIs. in
    • Decouple Robolectric.getForegroundThreadScheduler from ShadowApplication in
    • Add better concurrency support ShadowTypeface in
    • Add support for two additional Bitmap.createBitmap methods in
    • Fix ShadowResources.getSystem to fully update configuration/displayMetrics when the application is not yet loaded (@LazyApplication) in
    • ShadowAppWidgetManager: Added support for setting appWidgetOptions Bundle in
    • Explicitly load the application from the test rule if the test will run from a background thread in
    • Consolidate some Bitmap.createBitmap @Implementation methods in
    • Add PerfStats around installAndCreateApplication in
    • ShadowAppWidgetManager added implementation for isRequestPinAppWidgetSupported. in
    • Add setImportance and getImportance in ShadowNotificationManager in
    • Adding UserManager support for getSerialNumbersOfUsers on N+. in
    • Skip staged resources in the legacy resource system in
    • Extend shadow of RoleManager (Android Q+) to support IsRoleAvailable() in
    • Add perf stat for defining ProxyMaker classes in
    • Lazily create the WebViewFactoryProvider proxy in ShadowWebView in
    • Ensure that the Bitmap returned by Bitmap.extractAlpha is mutable in
    • Allow ShadowSmsManager to be extended in
    • Allow ShadowNotificationListenerService.addActiveNotification on given StatusBarNotification objects directly in
    • Avoid shadowing a constructor to get a Context object by @hoisie in
    • Use BufferedImage to scale bitmap by @utzcoz in
    • Improve naming of a ShadowAppWidgetManager shadow API method in
    • Run Java formatting on RoboCookieManager in
    • Expose the number of times NotificationListenerService#requestUnbind() is called. in
    • Make synchronization in ShadowContentResolver finer-grained to avoid a potential deadlock in
    • Fix a memory leak when destroying an activity. in
    • Use the stored Context in ShadowActivityManager in
    • Allow ShadowUsageStatsManager to record events happening at the same timestamp. in
    • Prefer the stored Application and Instrumentation in ShadowActivityThread in
    • Update MemoryLeaksTest to be extendable in
    • Use the stored Context in ShadowContentResolver in
    • Add a way to set ValueAnimator duration scales in
    • Decouple legacy background thread scheduler from ShadowApplication in
    • Add support for AppOpsManager.checkOp in ShadowAppOpsManager in
    • Allow expecting non-deterministic log messages using a regular expression pattern. in
    • Fix potential NPE in RequestMatcherBuilder in
    • Change @LazyApplication package to explicitly mark it as still experimental in
    • Added support for requestPinAppWidget to ShadowAppWidgetManager. in
    • Support custom futures in ShadowLegacyAsyncTask subclasses in
    • Add perf stat around ProxyMaker instance creation in
    • Add PhoneStateListner callback in setServerState. in
    • Add shadow implementation for BluetoothAdapter.getLeMaximumAdvertisingDataLength in
    • Update ShadowImsMmTelManager.createForSubscriptionId to call real impl in
    • Use internal system API Builder in BrightnessChangeEventBuilder in
    • Update ShadowAccessibilityButtonControllerTest to attach the service in
    • Update StorageVolumeBuilder for upcoming platform changes in
    • Prepare for upcoming platform changes in FrameMetricsBuilder in
    • Add support for registerCallbackWithEventMask in ShadowDisplayManagerGlobal in
    • Make ShadowTelecomManager#createLaunchEmergencyDialerIntent resilient to internal platform in
    • Set maxSdk in ShadowLauncherAppsTest.testGetActivityList to R in
    • Temporarily make WifiUsabilityStatsEntryBuilder extensible. in
    • Allow use of ShadowSystemVibrator.recordVibratePattern for subclasses. in
    • Add platform dependent features/implementations to ShadowRangingResult in
    • Add a test for ShadowFontBuilder in
    • Make ShadowAudioManager.createAudioPlaybackConfiguration extendable in
    • Update ShadowUsageStatsManager to @AutoValue. in
    • Use the real implementation of BlueoothAdapter.getDefaultAdapter in
    • Convert ShadowAsyncTaskBridge to reflector in
    • Save the last PendingIntent.onFinished callback passed to send in in
    • Use ShadowBluetoothAdapter state to implement enable/disable/isEnabled in
    • Prepare for Activity handling changes in platform. in
    • Add a getter and setter for CreateManageBlockedNumbersIntent in ShadowTelecomManager in
    • create ShadowVoiceInteractor for in robolectric shadows in
    • Add PerfStats to ShadowChoreographer.doFrame by @hoisie in
    • Use real Android framework code to create BluetoothLeScanner objects in
    • Update ShadowPhone to use the call list in Phone in
    • Include image data in the result of Bitmap.createBitmap with a source Bitmap in
    • Initialize the background thread scheduler from the main thread in
    • Remove redundant integration test. in
    • Adds a getId() method to ShadowCall. in
    • Support to handle emoji in xml by @utzcoz in
    • Don't call real TelephonyManager#requestCellInfoUpdate. in
    • Make RoboMonitoringInstrumentation inherit from Instrumentation directly in
    • getUserProfiles should return associated profiles when called from profile itself in
    • Update ShadowRangingResult for S in
    • Add ability to dump ProxyMaker generated classes in
    • Shadow additional ShortcutManager methods to prevent NPEs. in
    • Internal in
    • Simplify and future proof ShadowSpeechRecognizer#startListening. in
    • Add basic Robolectric support for EGL14 in
    • Use real method for BluetoothAdapter#getBluetoothLeAdvertiser. in
    • Migrate from deprecated JsonParser APIs to their replacements. in
    • Separate properties of ShadowLog with new lines (instead of commas) in toString() to make it easier to see boundaries of the message and throwable message + other misc cleanups. in
    • Add enableCarMode(priority, flags) to ShadowUIModeManager. in
    • Remove ShadowBluetoothAdapter.getBluetoothLeAvertiser in
    • Remove usage of InstrumentationProvider in AndroidTestEnvironment in
    • Use setup prepared fields for ShadowActivityManagerTest by @utzcoz in
    • Migrate tests from ShadowResourcesTest to ResourcesTest by @utzcoz in
    • Bump bouncycastle to 1.68 by @utzcoz in
    • Fixes an error when mocking a generic method with Mockk by @ogolberg in
    • Eagerly instantiate ActivityThread's main handler in
    • Shadow nativeGetTagsEnabled in
    • Migrate from deprecated Assert.assertThat([String, ]T, Matcher<T>) to MatcherAssert.assertThat([String, ]T, Matcher<T>). in
    • Change access of ShadowUIModeManager methods from public to protected. in
    • Update shadow implementation for ActivityManager.getHistoricalProcessExitReasons() in
    • Avoid a deadlock when an exception is thrown from an IdlingRunnable in
    • Add a few missing override implementations for startOpNoThrow and noteProxyOpNoThrow to ShadowAppOpsManager. in
    • Prepare for upcoming platform changes in BluetoothGatt in
    • Add name to ShadowSqliteConnection worker in
    • Include full exception stack trace in LogItem toString() in
    • Exit Looper.loop() when paused loopers are quit from their own thread. in
    • Update ShadowPaintTest to avoid Shadow.newInstanceOf in
    • Prepare for upcoming platform changes in Activity in
    • Add github action wrapper-validation-action by @utzcoz in
    • Bump buildSrc AGP to 4.1.3 by @utzcoz in
    • Remove ShadowIntrumentation#execStartActivityAsCaller by @utzcoz in
    • Fix and update the ShadowBluetoothAdapter resetter in
    • Add requestNetwork overloaded methods to ConnectivityManager in
    • Update ShadowLocationManager with R APIs. in
    • Allow createNotificationChannel(NotificationChannel) to update an existing channel in
    • Fixed issue of Robolectric tests failing with x11 error. in
    • Prepare for platform changes to WifiUsabilityStatsEntry in
    • Prepare for platform changes in PendingIntent in
    • Include ITetheringConnector as a service; otherwise TetheringManager creates a thread that polls forever looking for it. in
    • Update Bootstrap display configs in setQualifiers if the application isn't already loaded in
    • Move Robolectric-only resource tests back to ShadowResourcesTest by @hoisie in
    • Upgrade AndroidX Test dependency to 1.4.0-beta01 by @hoisie in
    • Restore test resources shortcuts.xml by @hoisie in
    • Shadow BluetoothAdapter#setScanMode with duration in SDK 30 by @jselbo in
    • Fix broken ShadowCookieManagerTest in
    • Add test failure diagnostics as suppressed exceptions, rather than throwing a new exception. in
    • Add count stats collection to reflection method calls in ReflectionHelpers in
    • Implement isNotificationListenerAccessGranted(ComponentName componentName). in
    • Updating error for unsupported background operations. in
    • Modifying ShadowDisplayEventReceiver to avoid CloseGuard warning in tests. in
    • Add capability to ShadowCameraManager to simulate disconnection events. in
    • Support a fluent API in StorageVolumeBuilder in
    • Update LazyApplication javadoc to remove references to Instrumentation in
    • Modifying ShadowInputEventReceiver to avoid CloseGuard warnings during tests. in
    • Add access to messages sent in ShadowContextHubClient in
    • Add a Builder for PreciseDataConnectionState in
    • Attempt #2 at properly propagating qualifiers when lazy loading in
    • Prevent setting multiple cookies in a single call to RoboCookieManager#setCookie by @utzcoz in
    • Squelch FragmentManager logging in BaseMemoryLeaksTest in
    • Add the implementation of ShadowInputMethodManager#getInputMethodList(). in
    • Restore LocaleList default after BootstrapTest.testUpdateDisplayResourcesWithDifferentLocale in
    • Don't cause NPE because of sorting null package names. in
    • Use a factory builder method in PreciseDataConnectionStateBuilder in
    • Fix memory leaks that can occur with lazy loading enabled in
    • Adding support for @Direct to replace directlyOn. in
    • Remove dead code in in
    • Annotate tests requiring legacy looper with @LooperMode(LEGACY) instead of using assume(...) in
    • Allows expecting certain tags with length > 23. in
    • Add the implementation of ShadowInputMethodManager#sendAppPrivateCommand(). in
    • Automated formatting for DisplayConfig and ShadowDisplay. in
    • Use real constructor for ViewConfiguration in
    • Add setPlaybackInfo() and implemented getPlaybackInfo() to in
    • Move test activities from integration_tests/ctesque into testapp in
    • Fix ShadowBluetoothLeScanner support for nullable parameters. in
    • Add display cutout to ShadowDisplay. in
    • Refactor the ChoreographerReflector to use @Direct for the doFrame reflector call in
    • Added RollbackInfoBuilder and PackageRollbackInfoBuilder to make rollback manager testing possible. in
    • Refresh BuildCompatTest in
    • Reset static LocaleList state after each test in
    • Reset CameraManager related state after each test in
    • Add a ctesque test for CookieManager in
    • Adding support for @ReflectorObject. in
    • Make ShadowWindowManagerGlobal.getWindowManagerService return the "real" service in
    • Add more shadow methods for BluetoothManager to make testing possible in
    • Add missed imports for testapp test Activity by @utzcoz in
    • Use UTC time zone explicitly for isEpoch test by @utzcoz in
    • Simplify PackageRollbackInfoBuilder build logic for SDK > Q in
    • Simplify ShadowBluetoothLeScanner APIs related to getting scan params in
    • Avoid reflection when constructing PorterDuffColorFilter objects in
    • Avoid reflection when constructing Event objects in ShadowEventLog in
    • Reset the locale to the initial value after each test in
    • Add a shadow for InputMethodManager.getCurrentInputMethodSubtype in
    • Remove deprecated ShadowBuild.Q in
    • suppress RobolectricSystemContext violations in
    • Add IIpSecService to the ShadowServiceManager. in
    • Update to androidx.test 1.4.0 + espresso 3.4.0 in
    • Running Google formatting on ShadowArscAssetManager files. by @hoisie in
    • Add StatsLog Shadow. in
    • Migrate the remainder of ActivityController to reflector in

    New Contributors

    • @ogolberg made their first contribution in

    Full Changelog:

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.6-alpha-2(Jun 11, 2021)

  • robolectric-4.6-alpha-1(May 9, 2021)

  • robolectric-4.5.1(Feb 2, 2021)

    This is a minor release that fixes a regression in 4.5 and removes some superfluous print statements. See and respectively for more details.

    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.5(Jan 22, 2021)

    Robolectric 4.5 adds support for Android API 30 (R final) and contains many bug fixes and other enhancements.

    More detailed release notes are forthcoming.

    For all changes view the comparison to 4.4.

    Use Robolectric:

    testCompile "org.robolectric:robolectric:4.5"
    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.5-beta-1(Jan 17, 2021)

  • robolectric-4.5-alpha-3(Nov 16, 2020)

  • robolectric-4.5-alpha-2(Nov 1, 2020)

  • robolectric-4.5-alpha-1(Sep 30, 2020)

  • robolectric-4.4(Aug 24, 2020)

    Robolectric 4.4 is a massive release in terms of improvements to Android compatibility. The most noticeable item in the release is that the new PAUSED looper mode is now the default. You can read about the PAUSED looper in more detail here:


    1. Not all changes are listed in the release notes. There were many other minor changes (such as dependency version bumps) that weren't included in this list for brevity. For all changes view the comparison to 4.3.1.
    2. Some of the pull requests in this release may contain duplicate changes from other pull requests in this release. We apologize for this messy history, it was the result of some misconfigured code sync tool. We’ve taken measures to ensure it doesn’t happen any more.

    Use Robolectric:

    testCompile "org.robolectric:robolectric:4.4"

    SDK/JVM support

    • Add support for Android Q final (#5289, #5292)
    • Support running on Java 11 (#5479, #5805)
    • Support running on Java 13 (#5550, #5786, #5805, #5819)


    • Deprecate LooperMode LEGACY in favor of PAUSED (#5490), and default to PAUSED looper mode (#5491)
    • Accessibility checking is now deprecated and has been moved into a separate maven artifact org.robolectric:plugin-accessibility-deprecated. Accessibility checking will be removed entirely from Robolectric 4.5. Please switch to Espresso for accessibility checking. (#5547)
    • Deprecate ShadowContentResolver shadow API because they do not work with ContentProviderClient (#5376)
    • Deprecate ShadowLocationManager.getLocationUpdateListeners and ShadowLocationManager.getLocationUpdateListeners (#5150)
    • Make it an error to run on Q with an unsupported java version instead of just silently skipping tests (#5290)
    • Deprecate Robolectric's custom cursor implementation (#5613)
    • The BouncyCastle security provider is now considered deprecated due to the incompatibility with Java 9+ (#5849, #5850). This was preventing Robolectric tests (and Robolectric itself) from making HTTPS network requests on Java 9+. Long term the plan is to switch to Conscrypt.

    Android support / Robolectric test API improvements

    • Fix bug in ShadowImageDecoder.decodeBitmap (#4966)
    • Use real setting for WIFI_SCAN_ALWAYS_AVAILABLE (#4968)
    • Add a shadow for Font.Builder (#4993)
    • Add killProcess implementation to ShadowProcess (#4985)
    • Add a shadow for CallLog.Calls (#4996)
    • Add a shadow for CallScreeningService (#4997)
    • Add several shadows for camera2 classes (#4874)
    • Add option to avoid calling ShadowApplication.onServiceDisconnected in ShadowApplication.unbindService (#4979)
    • Add ability to simulate Bluetooth unavailable in ShadowBluetoothAdapter (#5002)
    • Implement ShadowApplicationPackageManager.getApplicationIcon(ApplicationInfo) (#5005)
    • Add ability to simulate SecurityExceptions in bindService (#4980)
    • Add ability to simulate enabled/disabled networks in ShadowWifiManager (#4974)
    • Add ability to simulate wifi usability system APIs in ShadowWifiManager (#5168)
    • Add null check in ShadowWifiManager.addNetwork (#5014)
    • Add shadow implementation of ShadowTelephonyManager#getDataState (#5003)
    • Fall back to Android's implementation of getResourcesForApplication (#4969)
    • Implement ShadowTypeface.equals and ShadowTypeface.hashCode (#4992)
    • Add ability to make ShadowContentResolver.registerContentObserver throw an exception (#4988)
    • Implement ShadowSubscriptionManager.getActiveSubscriptionInfoCountMax (#5010)
    • Add ability to set system dialer package in ShadowTelecomManager (#4986)
    • Implement ShadowSensorManager.registerListener 5-arg overload (#5014)
    • Add ability to get last flags set in ShadowUIModeManager (#5027)
    • Add a shadow for BluetoothA2dp (#5034)
    • Add shadow implementation for BluetoothDevice.createRfcommSocketToServiceRecord (#5034)
    • Add shadow implementations for BluetoothDevice.setPin and BluetoothDevice.setPairingConfirmation (and ability to get the values set) (#5116)
    • Adding shadow implementations of BluetoothDevice.getAlias and BlueToothDevice.getAliasName and related test APIs (#5222)
    • Adds the ability to get broadcast intents sent to a specific user (#5045)
    • Validate intents passed to start/stop/bindService (#5053)
    • Complete rewrite of ShadowLocationManager to improve fidelity (#5035, #5062, #5152, #5587, #5666)
    • Add ability to clear broadcast intents in ShadowContextWrapper (#5066)
    • Fix package name ShadowApplicationPackageManager's Activity Chooser (#5068)
    • Add shadow implementation for MediaPlayer#setDataSource(Context, Uri) (#5064)
    • Add shadow implementation for UserManager.getUserHandle(int) (#5065)
    • Add shadow implementations for DevicePolicyManager.setSystemUpdatePolicy and DevicePolicyManager.getSystemUpdatePolicy (#5069)
    • Remove ShadowOverscroller (#5081)
    • Add ability to simulate return value of AccessibilityService.getWindows list in ShadowAccessibilityService (#5083)
    • Fix bug in ShadowParcel.writeByteArray (#5089)
    • Add shadow implementation for UserManager.getUserName (#5099)
    • Improve fidelity of ShadowTime#parse3339 (#5101)
    • Add shadow for BiometricManager (#5072)
    • Propagate RemoteException from Binder#onTransact method (#4984)
    • Add shadow for android.service.notification.NotificationListenerService.Ranking (#5113)
    • Add support for VibrationEffect.Prebaked in ShadowSystemVibrator (#5119
    • Add the ability to set Tx and Rx packets/bytes for ShadowTrafficStats (#5121)
    • Add shadow implementation for Activity.getCallingPackage (and the ability to set it) (#5126)
    • Add shadows for several telephony classes (android.telecom.Call, android.telecom.InCallAdapter, android.telecom.InCallService, android.telecom.Phone) (#5107)
    • Improve fidelity of ShadowCookieManager.removeSessionCookies (#5130)
    • Improve fidelity of OpEntry.getTime() and OpEntry.getDuration() in Q (#5133)
    • Set default NetworkCapabilities for the two Robolectric created Networks (#5129)
    • Set the mimetype in ShadowBitmapFactory.decodeStream() (#5128)
    • Add module support for ShadowPackageManager and ShadowApplicationPackageManager (#5136)
    • Add the ability to set the external storage directory in ShadowEnvironment (#5140)
    • Add support for the dataChanged API in ShadowBackupManager (#5137)
    • Add ShadowContentResolver.registerInputStreamSupplier (#5142)
    • Notify settings ContentResolver when settings change (#5138)
    • Include size and mtime members in Os.stat variants (#5148)
    • Implement ShadowInstrumentation.execStartActivity variant with UserHandle (#5096)
    • Add ability to add entries to ShadowDropBoxManager (#5160)
    • Fix ShadowSigningInfo parceling (#5163)
    • Add ability to set Build.VERSION.SECURITY_PATCH (#5173), Build.PRODUCT (#5304), Build.BRAND (#5566), and Build.HARDWARE (#5619)
    • Add support for DisplayManager BrightnessConfiguration APIs (#5170)
    • Add ability to simulate location power save modes in ShadowPowerManager (#5176)
    • Add shadow method and test API for PowerManager.isLightDeviceIdleMode (#5226)
    • Add support for Android Q usb port statuses in ShadowUsbManager (#5175)
    • Add ability to simulate sending and downloading multimedia messages in ShadowSmsManager (#5177)
    • Add ability to query the number of times a WebView was reloaded (#5182)
    • Add ability to simulate WebViewClient and WebViewClient callbacks on page loads (#5188, #5199)
    • Add shadow method for WebView.getTitle (#5200)
    • Add test APIs to check if WebViewDatabase.clearFormData was called (#5201)
    • Add ability to override autofill service component name to ShadowAutofillManager (#5181)
    • Add ability to construct AttestedKeyPair objects (#5183)
    • Add shadow method for CameraCaptureSessionImpl.capture (#5191)
    • Add shadow method and test APIs for MediaScannerConnection.scanFile (#5178)
    • Add synchronous support to ShadowMediaCodec and the ability to apply fake codecs (#5195)
    • Add shadow methods for CameraParameters metering and focus areas and test APIs (#5189)
    • Add shadow method for AudioManager.getActiveRecordingConfigurations and test APIs (#5198)
    • Add ShadowAudioRecord (#5202, #5789)
    • Add several shadow methods for SliceManager (#5227)
    • Add shadow methods for new Android Q variants of setPackagesSuspended (#5135)
    • Add shadow method and test APIs for AccessibilityManager.sendAccessibilityEvent (#5192)
    • Add ability to log time in ShadowLog (#5224)
    • Add shadow for SuspendDialogInfo system API (#5232)
    • Add shadow method for PackageManager.canonicalToCurrentPackageNames and the ShadowPackageManageraddCanonicalName test API (#5233)
    • Add better support for camera2 CaptureRequestBuilder (#5230)
    • Add shadow method for Os.sysconf and a shadow API to set sysconf values (#5247)
    • Add shadow method for PackageManager.setDistractingPackageRestrictions and shadow API to get the set value (#5248)
    • Add shadow method for Bitmap.extractAlpha(Paint, int[]) (#5240)
    • Add the ability to set the user id in ContextImpl (#5253)
    • Fix some bugs in ShadowStorageManager StorageVolume logic (#5251, #5250)
    • Add shadow method for Trace.isEnabled and shadow API to toggle the value (#5256)
    • Fix infinite loop when using CameraManager (#5269)
    • Add shadow class for MediaController (#5266, #5395)
    • Add shadow method for MediaMetadataRetriever.setDataSource and a shadow API to add bitmaps to a data source (#5279)
    • Add shadow method for MediaMetadataRetriever.getScaledFrameAtTime and the ability to set scaled frames (#5279)
    • Add shadow method for BluetoothDevice.getBluetoothClass and the ability to set the bluetooth class (#5277)
    • Add shadow methods for PendingIntent.readPendingIntentOrNullFromParcel and PendingIntent.writePendingIntentOrNullToParcel (#5283)
    • Improve fidelity of AccessibilityWindowInfo.equals (#5278)
    • Add shadow methods for DevicePolicyManager.bindDeviceAdminServiceAsUser and DevicePolicyManager.getBindDeviceAdminTargetUsers and a shadow API to set the authorized users for these methods (#5287)
    • Add shadow method for ContextImpl.getExternalCacheDirs (#5288)
    • Add shadow method for WebSettings.getDefaultUserAgent to prevent crash (#5294)
    • Add shadow method for MediaBrowserCompat.getSessionToken (#5301)
    • Add shadow method for VMRuntime.getCurrentInstructionSet and shadow API to set the current instruction set (#5318)
    • Add shadow methods for PowerManager.getCurrentThermalStatus, PowerManager.addThermalStatusListener, PowerManager.removeThermalStatusListener. Athermal, and a shadow API to set the current thermal status (#5297)
    • Add support for opening a ParcelFileDescriptor in truncate and append modes (#5322)
    • Add shadow method for UserManager.isUserUnlocked(UserHandle) and shadow API to set user unlocked status (#5323)
    • Improve fidelity of DateFormat.get*DateFormat( #5314)
    • Add shadows for ContextHubManager and ContextHubClient (#5340, #5399)
    • Add support for AudioPlaybackCallback in ShadowAudioManager (#5342)
    • Update many ShadowUserManager methods to support profiles and add shadow method for UserManager.isManagedProfile(int) (#5346)
    • Add shadow for RoleManager (#5357)
    • Add shadow method for AccountManager.addOnAccountsUpdatedListener and shadow API to notify the listeners (#5347)
    • Add shadow API to get AccountManager OnAccountsUpdateListeners (#5361)
    • Add shadow method TelephonyManager.requestCellInfoUpdate and a shadow API to set the cell infos for the callbacks (#5355)
    • Add shadow method for MediaCodec.getOutputFormat and the ability to set the output format (#5372)
    • Add shadow method for AudioManager.isBluetoothScoAvailableOffCall and shadow API to set the value (#5364)
    • Add more complete shadow implementation for TelecomManager.placeCall and shadow API to query information about outgoing calls (#5373)
    • Add shadow APIs for allowing and denying calls to ShadowTelecomManager (#5374)
    • Add shadow method for CrossProfileApps.startActivity and shadow APIs to peek/get/clear the started activities (#5387)
    • Add shadow API to get all available loopers (#5371)
    • Add shadow for (#5379)
    • Add shadow for (#5390, #5699)
    • Add shadow methods for View.addOnAttachStateChangeListener and View.removeOnAttachStateChangeListener and test API to get the OnAttachStateChangeListeners (#5401)
    • Throw IllegalArgumentException in PackageManager.getInstallerPackageName if package name is not installed (#5403)
    • Add shadow method for PackageManager.getUnsuspendablePackages (#5406)
    • Add static factory method ShadowSensorManager.createSensorEvent(int, int) that takes a sensor type (#5398)
    • Add shadow method for TelephonyManager.isRttSupported and a test API to set whether or not Rtt is supported (#5411)
    • Add shadow methods for NfcAdapter.enableReaderMode, NfcAdapter.disableReaderMode, and some shadow API to work with reader mode (#5405)
    • Add shadow for UserManager#isQuietModeEnabled (#5416)
    • Improve fidelity of MediaCodec.dequeueOutputBuffer (#5409, #5466)
    • Add shadow methods for AutofillManager.isAutofillSupported and AutofillManager.isEnabled and shadow API to set values returned (#5408)
    • Add shadow method for WifiRttManager.isAvailable (#5429)
    • Add shadow method for AccessibilityService.dispatchGesture and some shadow API to toggle and get the dispatched gestures (#5441)
    • Add shadow method for Adding TelephonyManager.sendDialerSpecialCode and shadow API to get the values sent (#5444)
    • Improve fidelity of Path copy constructor shadow implementation (#5444)
    • Add shadow method for (#5448)
    • Add shadow method for TelephonyManager.isHearingAidCompatibilitySupported and a shadow API method to set the value returned (#5450)
    • Add shadow methods for DevicePolicyManager.getAffiliationIds and DevicePolicyManager.setAffiliationIds (#5452)
    • Add shadow method for Canvas.drawRoundRect and shadow API to get information about the drawn round rects (#5451)
    • Add shadow method for UserManager.getProfileParent (#5457)
    • Add shadow method for DevicePolicyManager.isDeviceProvisioned and shadow API to set the value returned (#5461)
    • Add shadow methods for DevicePolicyManager.getPermissionPolicy and DevicePolicyManager.setPermissionPolicy in ShadowDevicePolicyManager (#5453)
    • Add a Configurer plugin that changes the behavior of the PackageManager.html.getInstallerPackageName shadow method to throw an exception (instead of returning null), which is consistent with real Android (#5465)
    • Add shadow API to optionally enforce a notification limit to NotificationManager.notify (#5467)
    • Fix triggering broadcasts from explicit intents if data on intent is specified (#5482)
    • Add shadow for android.telephony.ims.ImsMmTelManager system service and shadow API to set various pieces of state on the shadow (#5483, #5497)
    • Make ShadowTrace sections thread aware (#5494)
    • Fix permission check when matching broadcast receivers (#5495)
    • Refactor ShadowWrangler to delegate to a ShadowMatcher for making SDK-level decisions (f5371b525887dba3fc49f4d7765c88df8d11825a, dda47090be7dfdbd831397f3fa41c4dff25c24b4)
    • Add shadow for and shadow API to get the play counts (#5500)
    • Add shadow method for DownloadManager#setDestinationInExternalPublicDir (#5489)
    • Include StatusBarNotification post times in ShadowNotificationManager (#5519)
    • Add a more complete shadow method for TelecomManager.getDefaultOutgoingPhoneAccount and shadow API to to set (and reset) the default outgoing phone account (#5524)
    • Add shadow method for BluetoothAdapter.isLeExtendedAdvertisingSupported and shadow API to set the value returned (#5515)
    • Add shadow methods for AudioManager.registerAudioPolicy and AudioManager.unregisterAudioPolicy system APIs and shadow API to get information about the audio policies (#5538)
    • Add shadow methods for TrafficStats.setThreadStatsTag and TrafficStats.getThreadStatsTag (#5541)
    • Create separate cache directory for getExternalCacheDir instead of using the external storage root directory (#5534)
    • Use provided executor in TelephonyManager.requestCellInfoUpdate and add shadow API to set the error details for the callback (#5543)
    • Add more complete shadow methods for UserManager.isQuietModeEnabled and UserManager.requestQuietModeEnabled and shadow API to set whether a profile is locked (#5555)
    • Add support for CameraManager.openCamera for older SDKs (21-27) (#5551)
    • Add shadow method for CameraDeviceImpl.close (which is used in CameraDevice.close) (#5552)
    • Add shadow method for ConnectivityManager.getRestrictBackgroundStatus and shadow API to set the returned value (#5556)
    • Add shadow for android.service.voice.VoiceInteractionService and shadow APIs to get set UI hints and set the active service (#5537)
    • Add shadow method for AudioManager.generateAudioSessionId that returns monotonically increasing values (#5559)
    • Add shadow methods for NotificationManager.{getNotificationDelegate,canNotifyAsPackage,setNotificationDelegate} and shadow API ShadowNotificationManager.canNotifyAsPackage (#5565, #5573)
    • Add shadow method for PackageManager.getPackagesHoldingPermissions (#5568)
    • Add shadow method for TelephonyManager.getSimLocale and shadow API to set the returned value (#5582)
    • Add shadow method ConnectivityManager.getProxyForNetwork and shadow API to set the returned value (#5570)
    • Add shadow method for TelephonyManager.getDataNetworkType and shadow API to set the retired value (#5581)
    • Add shadow method for Paint.setUnderlineText (#5585)
    • Add support for MenuItem.setActionView(int) (#5603)
    • Add support for writing and reading FileDescriptors in Parcel. Specifically this adds shadow methods for Parcel.nativeWriteFileDescriptor and Parcel.nativeReadFileDescriptor (#5588)
    • Add shadow methods for DevicePolicyManager.isDeviceProvisioningConfigApplied and DevicePolicyManager.isDeviceProvisioningConfigApplied (#5599)
    • Better support reading/writing SharedMemory objects to Parcels (#5612, #5756)
    • Add shadow method for GradientDrawable.setStroke and shadow API methods to get the information about the stroke. (#5589)
    • Add shadow API for setting default user agent in ShadowWebSettings (#5615)
    • Add shadow method for TelephonyManager.isVoiceCapable and shadow API to set the value returned (#5606)
    • Add shadow method for Android P Typeface.create static factory method (#5616)
    • Add rudimentary support for Paint#breakText (#5607)
    • Add shadow methods for Environment.isExternalStorageLegacy (both no-arg and 1-arg variants) and shadow API to set the value returned (#5617)
    • Add shadow for android.service.voice.VoiceInteractionSession and many shadow API methods to work with the type (#5595)
    • Add shadow method for TelephonyManager.getCarrierIdFromSimMccMnc and a shadow API method to set the value returned (#5618)
    • Add shadow methods for WebView.goForward and WebView.canGoForward and shadow API to get the number of invocations of goForward (#5620)
    • Add shadow method for WebView.getHitTestResult and shadow API to set the value returned (#5630)
    • Add shadow for android.content.rollback.RollbackManager system API and some shadow API methods to get rollback information (#5621)
    • Add shadow for and make significant improvements to ShadowAudioEffect (#5591)
    • Add support for System.logW (#5634)
    • Add ShadowCamera.removeCamera shadow API for removing cameras (#5651)
    • Add an implementation for async setCookie to RoboCookieManager (#5653)
    • Support ADJUST_LOWER and ADJUST_RAISE in AudioManager.adjustStreamVolume shadow method (#5650)
    • Add shadow for android.bluetooth.le.BluetoothLeScanner and add shadow API to BluetoothAdapter to work with BluetoothLeScanner (#5659)
    • Add shadow method for TileService.startActivityAndCollapse(Intent) (#5664)
    • Add shadow API method ShadowWebView.pushEntryToHistory(String) to improve fidelity of history in a WebView (#5654)
    • Add builders for and and a shadow API method ShadowMediaCodecList.addCodec (#5705)
    • Update DeviceConfig to populate additional display metrics (#5706)
    • Improve fidelity of Activity#requestPermissions behavior (#5707)
    • Update ShadowPausedAsyncTaskLoader to allow setting a custom executor (#5708)
    • Improve fidelity of password tokens in DevicePolicyManager (#5693)
    • Add shadow methods for BluetoothA2dp.getConnectedDevices and BluetoothA2dp.getDevicesMatchingConnectionStates and shadow API to set the values returned (#5681)
    • Add shadow for (#5689)
    • Add shadow method for MediaCodec.native_flush (to support MediaCodec.flush) (#5698)
    • Add shadow methods for BluetoothHeadset.{startVoiceRecognition,stopVoiceRecognition,isAudioConnected} (#5660)
    • Add shadow for android.os.BugreportManager and some shadow API to query state and trigger callbacks for bug reports #5675)
    • Fix handling of null admin in DevicePolicyManager.isUninstallBlocked() (#5720)
    • Implement shadow method for ApplicationPackageManager.isInstantApp (#5725)
    • Improve fidelity related to input buffer ownership in ShadowMediaCodec (#5719)
    • Update ShadowSensorManager to support listeners registering more than one sensor type, as well as a shadow API method to query the registration for a (listener, sensor) pair (#5735)
    • Add shadow method for ContentResolver.query(Uri uri, String[], Bundle, CancellationSignal) (#5729)
    • Add SubscriptionInfoBuilder.setMcc and fix SubscriptionInfoBuilder.setMnc for SDK < Q (#5736)
    • Add shadow method for LauncherApps.isPackageEnabled (#5691)
    • Add shadow for (#5741)
    • Add shadow methods for WallpaperManager.setBitmap and WallpaperManager.getWallpaperFile and a shadow API method to get the set bitmap (#5750)
    • Add shadow methods for Android N system APIs ContextHubManager.getContextHubHandles and ContextHubManager.getContextHubInfo (#5760)
    • Add shadow method for Activity.reportFullyDrawn and shadow API to check whether this method has been called
    • Add shadow methods for UsageStatsManager.registerAppUsageLimitObserver, UsageStatsManager.unRegisterAppUsageLimitObserver, and shadow API to get the observers and trigger them (#5770)
    • Add shadow methods for DevicePolicyManager.{getShort,setShort,getLong,setLong}SupportMessage (#5776)
    • Add shadow methods for WallpaperManager.isWallpaperSupported and WallpaperManager.isSetWallpaperAllowed and shadow API to set the values returned (#5765)
    • Add shadow for, which includes the ability to create WiFI aware sessions (#5766)
    • Add shadow method for LauncherApps.getActivityList and test API to set the values returned (#5771)
    • Add shadow method for TileService#isLocked and shadow API to set the value returned (#5794)
    • Improve fidelity of BitmapFactory.decodeFile by attempting to use the real bitmap file width and height (#5774)
    • Add shadow methods for TextToSpeech.synthesizeToFile, TextToSpeech.isLanguageAvailable, TextToSpeech.setLanguage, and shadow APIs to configure the behavior of these methods (#5797)
    • Add shadow method for WallpaperManager.getWallpaperInfo and the ability for tests to specify the wallpaper service component (#5781)
    • Use loose signatures on ShadowTelephonyManager.requestCellInfoUpdate. This is to continue supporting Java 8 in Robolectric 4.4. (#5835)
    • Add shadow methods for InCallService.canAddCall, InCallService.setMuted, InCallService.setAudioRoute, InCallService.getCallAudioState, InCallService.requestBluetoothAudio, and some shadow API methods to modify the behavior of these methods (#5816)
    • Add shadow for (#5818, #5826)
    • Add shadow method of MediaPlayer.setDataSource(AssetFileDescriptor) (#5844)
    • Add shadow API to ShadowNetwork to determine whether a socket is bound, or how many sockets are bound (#5836)
    • Allow tests to configure value returned by P+'s Application.getProcessName (#5825)

    Misc improvements

    • Simplify single-parameter tests in ParameterizedRobolectricTestRunner (#5026)
    • Allow extension point for running custom actions for unsupported SDKs (#5028)
    • Fix SandboxClassLoader classloader inheritance (#5036)
    • Fix noisy NPE in ShadowInstrumentation (#5063)
    • Create Android application specified in package metadata (#5039)
    • Tolerate gaps between ZIP entries when jumping between Local File Headers (#5120)
    • Add extension points so child tests can be created (#5132)
    • Improve thread safety of many shadows (#5018, #5087, #5094, #5144, #5193, #5231, #5306, #5445, #5703, #5676, #5742)
    • Stop depending on javac annotation processing internals (#5155)
    • Add a way to specify classes to not instrument based on a regex (#5264)
    • Make reading binary resource zips more performant (#5309)
    • Fix issue transitioning to RESUMED state in ActivityScenario (#5332, #5331)
    • Add a plugin mechanism to provide a custom ShadowWrangler specialization (#5268)
    • Better support AssumptionViolatedException in RobolectricTestRunner (#5359, #5704)
    • Fix Util.getJavaVersion to support double-digit values (#5381)
    • Fix duplicate call to ContentProvider.onCreate (#5393)
    • Use AAPT for R class (and other cleanup) in tests (#5430)
    • Clean up autoservice usage and dependencies (#5432)
    • Mark fields and methods added to classes as synthetic (#5418)
    • Stop shadowing ApplicationPackageManager's constructor (#5455)
    • Upgrade to Android Gradle Plugin 3.5.3 and Gradle 5.4.1 (#5498)
    • CircleCI improvements (#5498, a64beaf3b91b566bd79116adc7ff4c798f393227, #5709, #5700, #5761, #5770, #5769 )
    • Run google-java-format check on CircleCI (#5769)
    • Add expectLogMessageWithThrowable to ExpectedLogMessagesRule (#5516) and other fixes/improvements to ExpectedLogMessagesRule (#5640, #5657, #5680)
    • Update BouncyCastle security provider due CVE-2018-1000613 (#5572)
    • Avoid instrumenting additional packages ** Jetpack Compose (#5622) ** io.mockk (#5169) ** org.bouncycastle and org.conscrypt (#5845)
    • Update RoboMonitoringInstrumentation to post shadowActivity.callOnActivityResult asynchronously (#5671, #5674)
    • Update ShadowServiceManager to lazily create binder proxies (#5716, #5714) and fix issues in ShadowServiceManager (#5717, #5722)
    • Use guava's ByteStreams to read and copy streams (#5726)
    • Preload in Android Q+ (#5733)
    • Fix Scheduler return values in PAUSED LooperMode, and support Scheduler#size (#5001)
    • Throw if ShadowPausedLooper APIs are used on a quit looper (#5499)
    • Removed the pegdown-doclet Markdown doclet gradle plugin due to Java 10+ incompatibility (#5743)
    • Converted all Robolectric Markdown Javadoc to regular Javadoc (#5746, #5747, #5753, #5759)
    • Add BackgroundTestRule to simplify running test code in a background thread (#5732)
    • Add BackgroundExecutor.runInBackground(Callable) helper method (similar to the existing BackgroundExecutor.runInBackground(Runnable) (#5730)
    • Improve support for MockK (#5169)
    • Fix 'Duplicate key' error when running ./gradlew upload (#5788)
    • Add robolectric.util.Logger.lifecycle method and use it to log some lifecycle events in RobolectricTestRunner (#5824)
    • Drop maven-ant-tasks dependency (due to CVE) and fetch from Maven manually (#5833, #5842, #5849, #5854, #5855)
    • Generate reflector class with valid access (#5841)
    • Add better support for Conscrypt (#5485
    • Fix problem mocking Java framework classes when using mockito-inline (#5875)
    Source code(tar.gz)
    Source code(zip)
  • robolectric-4.4-beta-1(Aug 17, 2020)

  • robolectric-4.4-alpha-5(Aug 13, 2020)

  • robolectric-4.4-alpha-4(Aug 13, 2020)

  • robolectric-4.4-alpha-3(Aug 13, 2020)

  • robolectric-4.4-alpha-2(Jul 23, 2020)

Android unit testing framework.
Fixtures for Kotlin providing generated values for unit testing

A tool to generate well-defined, but essentially random, input following the idea of constrained non-determinism.

Appmattus Limited 191 Dec 21, 2022
Selenium locators for Java/Kotlin that resemble the Testing Library (

Selenium Testing Library Testing Library selectors available as Selenium locators for Kotlin/Java. Why? When I use Selenium, I don't want to depend on

Luís Soares 5 Dec 15, 2022
PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

Writing unit tests can be hard and sometimes good design has to be sacrificed for the sole purpose of testability. Often testability corresponds to go

PowerMock 3.9k Jan 5, 2023
PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

Writing unit tests can be hard and sometimes good design has to be sacrificed for the sole purpose of testability. Often testability corresponds to go

PowerMock 3.9k Jan 2, 2023
Most popular Mocking framework for unit tests written in Java

Most popular mocking framework for Java Current version is 3.x Still on Mockito 1.x? See what's new in Mockito 2! Mockito 3 does not introduce any bre

mockito 13.6k Jan 4, 2023
A programmer-oriented testing framework for Java.

JUnit 4 JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. For more infor

JUnit 8.4k Jan 9, 2023
A programmer-oriented testing framework for Java.

JUnit 4 JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. For more infor

JUnit 8.4k Dec 28, 2022
Morsa: Jetpack Compose UI Testing Framework

Morsa: Jetpack Compose UI Testing Framework Test library to ease UI testing with Jetpack Compose Purpose This library aims to add some useful wrappers

HyperDevs 10 Dec 3, 2022
Snapshot Testing framework for Kotlin.

KotlinSnapshot Snapshot Testing framework for Kotlin. What is this? Snapshot testing is an assertion strategy based on the comparision of the instance

Pedro Gómez 157 Nov 13, 2022
3 types of Tests in Android (Unit - instrumentation - UI)

UnitTestingPractice 3 types of Tests in Android Unit instrumentation (Integration) UI Unit Testing benefits confirm code work like a charm simulate Ap

Ahmed Tawfiq 8 Mar 23, 2022
A simple project to help developers in writing their unit tests in Android Platform.

AndroidUnitTesting A simple project to help developers in writing their unit tests in Android Platform. This is not a multi-module project, but has th

Bruno Gabriel dos Santos 4 Nov 10, 2021
Kotlin wrapper for React Test Renderer, which can be used to unit test React components in a Kotlin/JS project.

Kotlin API for React Test Renderer Kotlin wrapper for React Test Renderer, which can be used to unit test React components in a Kotlin/JS project. How

Xavier Cho 7 Jun 8, 2022
Android UI Testing

User scenario testing for Android Robotium is an Android test automation framework that has full support for native and hybrid applications. Robotium

null 2.8k Dec 14, 2022
A set of AssertJ helpers geared toward testing Android.

AssertJ Android A set of AssertJ assertions geared toward testing Android. Deprecated The support libraries and play services are developing at a rate

Square 1.6k Jan 3, 2023
Android UI Testing

User scenario testing for Android Robotium is an Android test automation framework that has full support for native and hybrid applications. Robotium

null 2.7k Apr 8, 2021
A sample repo describing best practices for snapshot testing on Android

Road to effective snapshot testing A sample repo describing best practices for snapshot testing on Android. This includes for now: Parameterized Tests

Sergio Sastre Flórez 86 Jan 1, 2023
Testify — Android Screenshot Testing

Testify — Android Screenshot Testing Add screenshots to your Android tests Expand your test coverage by including the View-layer. Testify allows you t

ndtp 43 Dec 24, 2022
Turbine is a small testing library for kotlinx.coroutines Flow.

A small testing library for kotlinx.coroutines Flow

Cash App 1.8k Jan 5, 2023
Lovely Systems Database Testing

Lovely DB Testing This repository provides opinionated testing helpers for database testing used at Lovely Systems. License This plugin is made availa

Lovely Systems GmbH 1 Feb 23, 2022