Resources$NotFoundException when running Roboelectric test

放肆的年华 提交于 2019-11-29 13:44:30

It worked for me: add @Config(manifest = "src/main/AndroidManifest.xml")

@Config(manifest = "src/main/AndroidManifest.xml")
@RunWith(RobolectricTestRunner.class)
public class MainActivityTest {

    @Test
    public void testSomething() throws Exception {
        assertTrue(Robolectric.setupActivity(MainActivityTest .class) != null);
    }
}   

Note 1: If you are still getting the same error (happens when creating new project)

The Reason is related to different working directory & the answer is here: https://stackoverflow.com/a/31469526/4802664

Note 2: Using

Android Studio 3.0 (canary 9)
Gradle 4.1
Android Gradle plugin 3.0.0-alpha9
robolectric: 3.4.2

Gradle

buildscript {

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha9'
    }
}    

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'


    testImplementation 'junit:junit:4.12'

    // Espresso
    androidTestImplementation 'com.android.support.test:runner:1.0.0'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.0'

    // Robolectric
    testImplementation 'org.hamcrest:hamcrest-library:1.3'
    testImplementation 'org.robolectric:robolectric:3.4.2'
}
mihir raj

This plugin works for me when using custom RobolectricTestRunner and provide the missing system properties.

public class CustomRobolectricTestRunner extends RobolectricTestRunner {

  public CustomRobolectricTestRunner(Class<?> testClass) throws InitializationError {
    super(testClass);
    String buildVariant = BuildConfig.BUILD_TYPE + (BuildConfig.FLAVOR.isEmpty()? "" : "/" + BuildConfig.FLAVOR);
    System.setProperty("android.package", BuildConfig.APPLICATION_ID);
    System.setProperty("android.manifest", "build/intermediates/manifests/full/" + buildVariant + "/AndroidManifest.xml");
    System.setProperty("android.resources", "build/intermediates/res/" + buildVariant);
    System.setProperty("android.assets", "build/intermediates/assets/" + buildVariant);
  }
}

Edit: You must also use a different working directory at your unit test run configuration. Best is to change the default configuration and use $MODULE_DIR$ https://code.google.com/p/android/issues/detail?id=158015#c5

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