Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

android - Resources$NotFoundException when running Roboelectric test

I've just set up Roboelectric 3.2.2 with a new app and I have written my first simple test:

@RunWith(RobolectricTestRunner.class)
@Config(manifest="src/main/AndroidManifest.xml",
    packageName="my.pacakge.name.debug")
public class MainActivityTest {

    @Test
    public void clickButton() {
        MainActivity mainActivity = Robolectric.setupActivity(MainActivity.class);
        String text = ((TextView)mainActivity.findViewById(R.id.text_main)).getText().toString();
        assertEquals("Should equal Hello World!", "Hello World!", text);
    }
}

I've followed all the set up and instructions here and here but I am still getting this error every time I try to run the test:

android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0 in packages [android, my.package.name.debug]

This exception occurs at the first line of the test where I am calling setupActivity().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...