我创建了一个新的 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/