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

风流意气都作罢 提交于 2019-11-29 02:49:05

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
  }
}

If your build fails due to an AAPT2 resource processing issue or you want to use Roboelectric, you can disable AAPT2 by setting android.enableAapt2=false in your gradle.properties file and restarting the Gradle daemon by running ./gradlew --stop from the command line.

Official guideline Android Studio 3.0 Release

(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.

I was using espresso, and for that you needed to use app resources, not test resources.

So instead of

InstrumentationRegistry.getInstrumentation().context.resources.getString("key")

I used

activityRule.activity.getString("key")

In my case the following solved my issue: "Problem is related to android studio. Go to 'Run' -> 'Edit configurations...' and change 'Working directory' value to $MODULE_DIR$

Run your tests.

More info here under 'Building with Android Studio'."

reference: https://github.com/robolectric/robolectric/issues/2653

You can also try @Config(manifest = "<projectFolder>/src/main/AndroidManifest.xml") in the case that you can not simply include the resources as some projects tests will fail with that included.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!