运行 Roboelectric 测试时的 Resources$NotFoundException [英] Resources$NotFoundException when running Roboelectric test

查看:21
本文介绍了运行 Roboelectric 测试时的 Resources$NotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚用一个新应用程序设置了 Roboelectric 3.2.2,我已经编写了我的第一个简单测试:

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]

此异常发生在我调用 setupActivity() 的测试的第一行.

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

推荐答案

它对我有用: 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);
    }
}   

注意 1:如果您仍然遇到相同的错误(在创建新项目时发生)

原因与不同的工作目录有关答案在这里:https://stackoverflow.com/a/31469526/4802664

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

注意 2:使用

Android Studio 3.0(金丝雀9)
摇篮 4.1
Android Gradle 插件 3.0.0-alpha9
机器人电子:3.4.2

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

这篇关于运行 Roboelectric 测试时的 Resources$NotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆