7

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

@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);
    }
}

我已按照此处此处的所有设置和说明进行操作,但每次尝试运行测试时仍然出现此错误:

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

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

4

2 回答 2

2

它对我有用:添加@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

注2:使用

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

摇篮

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'
}
于 2017-08-08T15:03:01.957 回答
0

当使用自定义 RobolectricTestRunner 并提供缺少的系统属性时,此插件对我有用。

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);
  }
}

编辑:您还必须在单元测试运行配置中使用不同的工作目录。最好是更改默认配置并使用 $MODULE_DIR$ https://code.google.com/p/android/issues/detail?id=158015#c5

于 2017-02-16T19:26:39.587 回答