我只想测试获取String资源等于我认为应该相等的值。我的问题似乎是我的项目中有Realm。我知道Robolectric不支持Realm(它在文档中说明了它),但我根本没有调用Realm,所以我觉得可能有办法做到这一点。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "app/src/main/AndroidManifest.xml")
public class ResourceTester {
@Test
public void testingString() {
String resourceString = RuntimeEnvironment.application.getString(R.string.app_name);
assertEquals(resourceString, "Yeah");
}
}
确实看起来 IS 试图调用Realm
java.lang.UnsatisfiedLinkError: Can't load library:
/var/folders/3x/ddxtg5fs1hxgqrp6h63vsc140000gp/T/android-tmp-
robolectric3612430387389787158/app_lib/librealm-jni.dylib.3.5.0
编辑:我尝试了更多的东西,似乎在@Config注释中设置manifest
是问题,但后来我得到了android.content.res.Resources$NotFoundException: unknown resource 2131362072
还有其他想法吗?我可以创建另一个Realm
未被调用的应用程序类吗? / test目录如何知道?
为大卫编辑:
我试过了:
@RunWith(RobolectricGradleTestRunner.class)
@Config(application = TestingApplication.class, constants = BuildConfig.class, sdk = 21)
public class ResourceTester {
@Test
public void newTestingTests() throws Exception {
String appName = RuntimeEnvironment.application.getString(R.string.app_name);
}
}
但我得到了:
android.content.res.Resources$NotFoundException: unknown resource 2131362072
如果我将其更改为
@RunWith(RobolectricTestRunner.class)
//@RunWith(RobolectricGradleTestRunner.class)
@Config(application = TestingApplication.class, constants = BuildConfig.class, sdk = 21)
public class ResourceTester {
@Test
public void newTestingTests() throws Exception {
String appName = RuntimeEnvironment.application.getString(R.string.app_name);
}
}
我得到了
WARNING: No manifest file found at ./AndroidManifest.xml.Falling back to the Android OS resources only.
To remove this warning, annotate your test class with @Config(manifest=Config.NONE).
android.content.res.Resources$NotFoundException: unknown resource 2131362072
答案 0 :(得分:8)
如果您有一个重量级的Application类(例如,依赖于Realm,Crashlytics等)并且您的单元测试没有引用这些,您可以在配置中使用android.app.Application
作为您的Application类:
@RunWith(RobolectricTestRunner.class)
@Config(application = android.app.Application.class, manifest="src/main/AndroidManifest.xml", sdk = 23)
public class ResourceTester {
如果您按照sum
Working Directory
设置为$MODULE_DIR$