android - Robolectric 找不到资源或 list 文件

标签 android android-manifest robolectric

我创建了一个新的 TestProject 并在我的 testMethod 中添加了以下行:

Robolectric.getShadowApplication().getString(R.string.mystring);

我的测试失败了

android.content.res.Resources$NotFoundException: unknown resource 2131558482

控制台显示以下警告:

WARNING: No manifest file found at .\..\..\MyProject\AndroidManifest.xml.Falling back to the Android OS resources only.
To remove this warning, annotate your test class with @Config(manifest=Config.NONE).
WARNING: no system properties value for ro.build.date.utc

AndroidManifest.xml 是否需要获取字符串资源? 我尝试通过 org.robolectric.Config.properties@Config 添加 Manifest,但警告仍然出现,我无法获取字符串资源。我确保 list 的相对路径是正确的。 我还尝试更改 JUnit 运行配置,但这没有帮助。

最佳答案

这里描述的问题的解决方案: http://blog.futurice.com/android_unit_testing_in_ides_and_ci_environments

失踪的 list

您现在应该已经注意到 Robolectric 提示无法找到您的 Android Manifest。我们将通过编写自定义测试运行器来解决这个问题。将以下内容添加为 app/src/test/java/com/example/app/test/RobolectricGradleTestRunner.java:

package com.example.app.test;

import org.junit.runners.model.InitializationError;
import org.robolectric.manifest.AndroidManifest;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.res.Fs;

public class RobolectricGradleTestRunner extends RobolectricTestRunner {
  public RobolectricGradleTestRunner(Class<?> testClass) throws InitializationError {
    super(testClass);
  }

  @Override
  protected AndroidManifest getAppManifest(Config config) {
    String myAppPath = RobolectricGradleTestRunner.class.getProtectionDomain()
                                                        .getCodeSource()
                                                        .getLocation()
                                                        .getPath();
    String manifestPath = myAppPath + "../../../src/main/AndroidManifest.xml";
    String resPath = myAppPath + "../../../src/main/res";
    String assetPath = myAppPath + "../../../src/main/assets";
    return createAppManifest(Fs.fileFromPath(manifestPath), Fs.fileFromPath(resPath), Fs.fileFromPath(assetPath));
  }
}

记得更改测试类中的 RunWith 注解。

关于android - Robolectric 找不到资源或 list 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18715983/

相关文章:

java - Here-API:PDE 请求返回 GeoboundingBox 之外的 POI

java - Robolectric 测试从小部件启动的 Activity

android - 如何在 gridView 中更快地加载应用程序的图像(图标)?

android - fragment 中的空指针异常

使用 GPS 的 Android App 功耗

java - 启动画面错误

android - 通过 ADB 安装新的启动器应用程序时,未清除家庭默认应用程序

android-manifest - 如何使用 android :launchMode ="singleInstance" 在 Flutter 中处理来自外部应用程序的传入 Intent

java - 如何仅在测试运行时忽略类或方法

安卓 TDD : The saga continues with Robolectric & Gradle