Make Robolectric compatible with latest Gradle tools (3.0.0)

Olivier Goutay
AndroidPub
Published in
2 min readSep 7, 2017

If you experience `android.content.res.Resources$NotFoundException` while trying to run your Robolectric tests, this is probably related to the issue described in this article.

I wrote this short article in case you were looking for a solution: how to make Robolectric 3.4.2 compatible with the new Gradle tools (3.0.0-beta4) at the time of writing this article.

What changed?

Before, Robolectric was getting the resources path from the BuildConfig class (concatenating build type, flavor, version etc…) to know where the intermediate resources folder was located.
Starting Android Studio 3.0, AAPT got updated and supports incremental resources build. It’s great, but the problem is that AAPT2 does not generate resources like before, and does not use intermediate folder.

By the way, AAPT stands for Android Asset Packaging Tool, and is notably used to compile resources (strings, layouts etc..) into binary assets.

The solution

The solution is either to disable AAPT2 (not really a solution right?) or to update to gradle 3.0.0 and update Robolectric.

To upgrade your gradle tools to 3.0.0, the situation is really gonna depend on the current dependencies in your project and how well they support this new version. Please see the end of this article for one official guide (not complete unfortunately).

Also, be sure to use the latest version (at this time) of Robolectric: 3.4.2

Last step is to add this code to your app build.gradle:

android {
testOptions {
unitTests {
includeAndroidResources = true
}
}
}

It basically provides, out of the gradle box, resources for unit tests.

References

AAPT2 update: https://androidstudio.googleblog.com/2017/06/android-studio-30-canary-5-is-now.html)
Robolectric updated documentation: http://robolectric.org/getting-started/
Robolectric issue: https://github.com/robolectric/robolectric/issues/3169,
Upgrade to Gradle 3.0.0: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

--

--

Olivier Goutay
AndroidPub

Senior Software Engineer @ Solana Labs | Ex-Netflix | Ex-Mentor at Code2040