Robolectric无法正确处理getApplicationContext()-NPE [英] Robolectric not handling getApplicationContext() correctly - NPE

查看:104
本文介绍了Robolectric无法正确处理getApplicationContext()-NPE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在使用Robolectric的android应用程序上运行了一些测试,并且到目前为止一直运行良好.

I've been running some tests on an android application using Robolectric and it's been working well until now.

我的应用程序将getApplicationContext()的结果传递给构造函数,但是Robolectric应该确保此值不为null,因为我正在使用BuildActivity()方法.该错误是由于我的测试环境的某些配置引起的,或者是Robolectric中的错误.结果是Toast的构造函数中的NullPointerException.

My application passes the result of getApplicationContext() to a constructor, but Robolectric should be ensuring the value of this is not null as I am using the BuildActivity() method. The error is in some configuration of my test environment, or a bug in Robolectric. The result is a NullPointerException in the constructor of Toast.

我的环境:

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

我正在尝试测试我们的类SystemMonitorActivity,它是抽象的

I'm trying to test our class SystemMonitorActivity, which is abstract

public abstract class SystemMonitorActivity extends BaseActivity implements OnClickListener

BaseActivity:

BaseActivity:

public class BaseActivity extends Activity implements IHandleMessageReceived, Thread.UncaughtExceptionHandler

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

I've created a subclass of SystemMonitorActivity so that I can instantiate it in my tests:

public class SystemMonitorActivitySubclass extends SystemMonitorActivity

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

Here is my mock test class to reproduce the error I am seeing:

@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资源:

I've made sure to include the Android resources in my tests in build.gradle:

android.testOptions.unitTests.includeAndroidResources = true

是否可能需要以某种方式将SystemMonitorActivitySubclass添加到AndroidManifest.xml?

Could it be that I need to add SystemMonitorActivitySubclass to the AndroidManifest.xml somehow?

在整个堆栈跟踪过程中,实际的NPE发生在以下代码片段中:

Working our way through the stack trace, the actual NPE occurs in this snippet of code:

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召唤来的人

Which is called from 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:

Context being passed to makeText is getApplicationContext(), which should be handled by Robolectric to ensure it is not 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个多小时,而且我觉得更接近找出问题所在.非常感谢您的帮助!

I've been debugging this for 6+ hours now and I don't feel any closer to figuring out what the issue is. Any help is much appreciated, thanks!

更新:我已经尝试按照安东·马利舍夫(Anton Malyshev)的建议使用以下方法

UPDATE: I've tried the following approach as suggested by 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)

推荐答案

似乎您忘记了在.get()之前调用.start()的原因,因此在访问Toast内部的context时出现NullPointerException,请检查文档: http://robolectric.org/activity-lifecycle/

Seems you forgot to call .start() before .get(), so you're getting NullPointerException on accessing the context inside Toast, check the docs: http://robolectric.org/activity-lifecycle/

所以我建议改变

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

收件人:

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

也许最好还保留ActivityController引用(在其示例代码中).

Probably it's better to keep ActivityController reference as well (as in their sample code).

这篇关于Robolectric无法正确处理getApplicationContext()-NPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆