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

后端 未结 8 1668
别那么骄傲
别那么骄傲 2020-12-15 03:08
Android Studio 3.0 Beta2
classpath \'com.android.tools.build:gradle:3.0.0-beta3\'
testCompile \'org.robolectric:robolectric:3.4.2\'

Test class that

相关标签:
8条回答
  • 2020-12-15 03:34

    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
    
    0 讨论(0)
  • 2020-12-15 03:34

    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.

    0 讨论(0)
  • 2020-12-15 03:36

    Not a direct answer to the question, but if you are testing something that needs a context to query resources against I have found the following to work quite well:

    ApplicationProvider.getApplicationContext()
    

    (or RuntimeEnvironment.application -- but this is deprecated in favor of the above)

    0 讨论(0)
  • 2020-12-15 03:38

    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")
    
    0 讨论(0)
  • 2020-12-15 03:44

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

    0 讨论(0)
  • 2020-12-15 03:45

    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

    0 讨论(0)
提交回复
热议问题