Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.content.res.Resources$NotFoundException in Robolectric 2.4

I have trouble loading resources when running unit tests from command line. It works fine in IntelliJ.

I'm using:

  • com.android.tools.build:gradle:1.1.3
  • org.robolectric:robolectric-gradle-plugin:1.0.1
  • org.robolectric:robolectric:2.4

I have the following project structure (Multi-module):

+---module1
|   |   build.gradle
    |   \---src
    |       +---main
    |       |   |   AndroidManifest.xml
    |       |   |   
    |       |   +---res
    |       |   |   \---values
    |       |   |           strings.xml
    |       \---test
    |           \---java
    |               \---example
    |                    |   FooTest.java
+---module2
etc

My test (simplified) looks like this:

@Config(emulateSdk = 18, reportSdk = 18, manifest = "./src/main/AndroidManifest.xml")
@RunWith(RobolectricTestRunner.class)
public class FooTest {

    @Test
    public void test() {
        String result = Robolectric.application.getString(R.string.error_message);

         assertThat(result, notNullValue());
    }
 }

I get this stacktrace:

android.content.res.Resources$NotFoundException: unknown resource 2131361826
at org.robolectric.shadows.ShadowAssetManager.getAndResolve(ShadowAssetManager.java:311)
at org.robolectric.shadows.ShadowAssetManager.getResourceText(ShadowAssetManager.java:69)
at android.content.res.AssetManager.getResourceText(AssetManager.java)
at android.content.res.Resources.getText(Resources.java:235)
at org.robolectric.shadows.ShadowResources.getText(ShadowResources.java:363)
at android.content.res.Resources.getText(Resources.java)
at android.content.res.Resources.getString(Resources.java:325)
at org.robolectric.shadows.ShadowContext.getString(ShadowContext.java:41)
at org.robolectric.shadows.ShadowContextWrapper.getString(ShadowContextWrapper.java:96)
at android.content.Context.getString(Context.java)

Note: I'm quite new to Gradle so it is likely that there is a misconfiguration somewhere. I have assumed that by following the project structure convention that I don't need to specify where to find resources. I tried specifying them but without any luck:

android {
    sourceSets {
        main {
            manifest.srcFile 'src/main/AndroidManifest.xml'
            java.srcDirs = ['src/main/java']
            res.srcDirs = ['src/main/res']
            assets.srcDirs = ['src/main/assets']
        }
    }
}
like image 682
Alix Avatar asked Apr 09 '15 08:04

Alix


1 Answers

During investigation we found the cause of problem. If you use android gradle plugin v1.1.x then you don't need in common robolectric gradle plugin.

Be carefull that incorrect version of robolectric gradle plugin will break your tests.

like image 51
Eugen Martynov Avatar answered Oct 20 '22 12:10

Eugen Martynov