Robolectric: Resources$NotFoundException: String resource ID with Android Gradle Plugin 3

As mentioned by an engineer from Google team (most possibly Xavier Ducrohet), Robolectric has issues with AAPT2:

Robolectric is not compatible with aapt2.

Two options here.

First option - follow Robolectric guidelines for Android Studio 3.0+

Add the following to your build.gradle:

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

Annotate your test with the Robolectric test runner:

@RunWith(RobolectricTestRunner.class)
public class SandwichTest {
}

Second option: disable AAPT2 adding following line into gradle.properties file:

android.enableAapt2=false

The Robolectric documentation states that the following configuration should be used with Android Studio 3.x:

android {
  testOptions {
    unitTests.includeAndroidResources true
  }
}

(for anyone that might be looking for a solution to a similar problem)


Be sure to use

RuntimeEnvironment.application

and not:

RuntimeEnvironment.systemContext

when you're trying to resolve resources "manually".

That's one case in which Resources$NotFoundException might show up with Robolectric.