我在我的应用程序中遇到了一个奇怪的错误。我有一个MyApplication
类扩展Application
。在它的onCreate()
方法中,我初始化了一些需要将 API 密钥存储在字符串资源文件中的第 3 方库。基本上,它在我可以测试的设备上运行良好:Nexus S 和 Galaxy SIII。但是我从崩溃报告系统中得到了几个条目,如果我运行 Robolectric 测试,MyApplication.onCreate()
我会从getString()
方法中得到 NullPointerException。
我想知道是否有人有同样的问题,可能是什么原因?
测试的日志输出(崩溃报告也参考 中的同一行setupAnalyticsCrashReportingAndThirdPartySdks
):
java.lang.NullPointerException
at org.robolectric.shadows.ShadowResources.getResName(ShadowResources.java:100)
at org.robolectric.shadows.ShadowResources.getString(ShadowResources.java:130)
at android.content.res.Resources.getString(Resources.java)
at org.robolectric.shadows.ShadowContext.getString(ShadowContext.java:54)
at android.content.Context.getString(Context.java)
at com.myapp.android.MyApplication.setupAnalyticsCrashReportingAndThirdPartySdks(MyApplication.java:113)
at com.myapp.android.MyApplication.onCreate(MyApplication.java:42)
at com.myapp.android.util.UtilitiesTest.setUp(UtilitiesTest.java:44)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:106)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
更新:一小段代码:
public class MyApplication extends Application
{
private static MyApplication _instance;
@Override
public void onCreate()
{
super.onCreate();
setupAnalyticsCrashReportingAndThirdPartySdks();
}
public MyApplication()
{
_instance = this;
}
public static MyApplication getInstance()
{
return _instance;
}
private void setupAnalyticsCrashReportingAndThirdPartySdks()
{
String env = getString(R.string.environment); // Crash here
if (env != null && env.equalsIgnoreCase("dev"))
{
FlurryAnalytics.setDebugMode(true);
}
}
}