Robolectric无法正确处理getApplicationContext() - NPE

时间:2018-01-22 15:39:36

标签: java android unit-testing junit robolectric

我使用Robolectric在Android应用程序上运行了一些测试,直到现在它一直运行良好。

我的应用程序将getApplicationContext()的结果传递给构造函数,但是当我使用BuildActivity()方法时,Robolectric应该确保它的值不为null。错误发生在我的测试环境的某些配置中,或者是Robolectric中的错误。结果是Toast的构造函数中的NullPointerException。

我的环境:

com.android.tools.build:gradle:3.0.1
org.robolectric:robolectric:3.4.2
junit:junit:4.12

我试图测试我们的类SystemMonitorActivity,它是抽象的

public abstract class SystemMonitorActivity extends BaseActivity implements OnClickListener

BaseActivity:

public class BaseActivity extends Activity implements IHandleMessageReceived, Thread.UncaughtExceptionHandler

我已经创建了SystemMonitorActivity的子类,以便我可以在我的测试中实例化它:

public class SystemMonitorActivitySubclass extends SystemMonitorActivity

这是我的模拟测试类,用于重现我看到的错误:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class BuildActivityTest {

    @Test
    public void onCreateTest000() throws Exception {
        SystemMonitorActivitySubclass systemMonitorActivitySubclass = Robolectric.buildActivity(SystemMonitorActivitySubclass.class).create().get();
    }

}

我的测试结果:

java.lang.NullPointerException
    at android.widget.Toast.__constructor__(Toast.java:114)
    at android.widget.Toast.<init>(Toast.java)
    at org.robolectric.shadows.ShadowToast.makeText(ShadowToast.java:38)
    at android.widget.Toast.makeText(Toast.java)
    at com.siemens.hc.poc.isf.admin.sysmon.SystemMonitorActivity.setUpDeviceOwner(SystemMonitorActivity.java:649)
    at com.siemens.hc.poc.isf.admin.sysmon.SystemMonitorActivity.onCreate(SystemMonitorActivity.java:401)
    at android.app.Activity.performCreate(Activity.java:6975)
    at org.robolectric.util.ReflectionHelpers.callInstanceMethod(ReflectionHelpers.java:232)
    at org.robolectric.android.controller.ActivityController$1.run(ActivityController.java:73)
    at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:366)
    at org.robolectric.shadows.CoreShadowsAdapter$1.runPaused(CoreShadowsAdapter.java:27)
    at org.robolectric.android.controller.ActivityController.create(ActivityController.java:70)
    at org.robolectric.android.controller.ActivityController.create(ActivityController.java:80)
    at com.siemens.hc.poc.isf.admin.sysmon.BuildActivityTest.setUp(BuildActivityTest.java:63)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:228)
    at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:110)
    at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:37)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:64)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:108)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)

我确保在build.gradle的测试中包含Android资源:

android.testOptions.unitTests.includeAndroidResources = true

难道我需要以某种方式将SystemMonitorActivitySubclass添加到AndroidManifest.xml吗?

通过堆栈跟踪工作,实际的NPE出现在这段代码中:

java.lang.NullPointerException
    at android.widget.Toast.__constructor__(Toast.java:114)

public Toast(@NonNull Context context, @Nullable Looper looper) {
    mContext = context;
    mTN = new TN(context.getPackageName(), looper);
    ...

从Robolectrics ShadowToast调用:

at android.widget.Toast.<init>(Toast.java)
at org.robolectric.shadows.ShadowToast.makeText(ShadowToast.java:38)

@Implementation
public static Toast makeText(Context context, CharSequence text, int duration) {
    Toast toast = new Toast(context);
    ...

传递给makeText的上下文是getApplicationContext(),应由Robolectric处理,以确保它不为null:

at android.widget.Toast.makeText(Toast.java)
at com.siemens.hc.poc.isf.admin.sysmon.SystemMonitorActivity.setUpDeviceOwner(SystemMonitorActivity.java:649)

Toast.makeText(getApplicationContext(), "Not a device owner", Toast.LENGTH_SHORT).show();

我现在已经调试了6个多小时了,而且我觉得不知道问题是什么了。非常感谢任何帮助,谢谢!

更新:我已按照Anton Malyshev的建议尝试了以下方法

@Test
public void onCreateTest000() throws Exception {
    ActivityController controller = Robolectric.buildActivity(SystemMonitorActivitySubclass.class).create().start();
    Activity activity = (Activity)controller.get();
}

这有相同的结果;

java.lang.NullPointerException
at android.widget.Toast.__constructor__(Toast.java:114)

1 个答案:

答案 0 :(得分:0)

似乎您忘记在.start()之前致电.get(),因此您在访问context内的Toast时收到NullPointerException,请查看文档: http://robolectric.org/activity-lifecycle/

所以我建议改变

systemMonitorActivitySubclass = Robolectric.buildActivity(SystemMonitorActivitySubclass.class).create().get();

为:

systemMonitorActivitySubclass = Robolectric.buildActivity(SystemMonitorActivitySubclass.class).create().start().get();

保留ActivityController引用也可能更好(如示例代码所示)。