- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我一直在使用 Robolectric 在 Android 应用程序上运行一些测试,到目前为止一直运行良好。
我的应用程序将 getApplicationContext() 的结果传递给构造函数,但 Robolectric 应该确保该值不为 null,因为我正在使用 BuildActivity() 方法。该错误出在我的测试环境的某些配置中,或者是 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
基本 Activity :
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 出现在以下代码 fragment 中:
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)
最佳答案
似乎您忘记在 .get()
之前调用 .start()
,因此您在访问 Toast
内的 context
时遇到 NullPointerException,请检查文档: http://robolectric.org/activity-lifecycle/
所以我建议改变
systemMonitorActivitySubclass = Robolectric.buildActivity(SystemMonitorActivitySubclass.class).create().get();
至:
systemMonitorActivitySubclass = Robolectric.buildActivity(SystemMonitorActivitySubclass.class).create().start().get();
也许最好也保留 ActivityController
引用(如示例代码中所示)。
关于java - Robolectric 未正确处理 getApplicationContext() - NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48385221/
目前,我的经验是,一段利用Google Drive API的代码在没有引入ProGuard的情况下运行得很好。。然而,在引入ProGuard之后,我得到了以下运行时错误。。请注意,崩溃发生在我的代码(
今天早上我遇到了一个非常奇怪的 NPE,并将其简化为一个简单的示例。这是 JVM 错误还是正确的行为? public class Test1 { class Item { In
在 crashlytics 中报告的 NPE 仅适用于 Android O 及更高版本。我只是在 onCreate 方法中 startForegroundService 和服务 startForgro
运行以下内容: public class NPESample { String value; public static void main(String[] args) { NPES
我有一个非常简单的 OpenAPI/Swagger 配置 (openapi.yaml): swagger: '2.0' info: title: My Service version: 1.0
我正在使用 com.sun.media.imageioimpl.plugins.tiff.TIFFPackBitsCompressor 尝试对使用 PackBits 的 tiff 字节数组进行编码。我
这个问题已经有答案了: What is a NullPointerException, and how do I fix it? (12 个回答) findViewById returns null
我有一个处理大量数据的批处理作业。该作业基本上从源数据库获取数据并进行 Web 服务调用,然后将数据写入目标数据库。今天我遇到了“NPE”,我在其中检查 XML 是否有“成功”响应。我检查其中一个节点
这个问题已经有答案了: Why does a ternary conditional expression returning null and assigned to a reference typ
这个问题已经有答案了: What is a NullPointerException, and how do I fix it? (12 个回答) 已关闭 4 年前。 我正在尝试从 bundle 内的
我试图在我的应用程序中每隔一分钟执行一项任务,我使用以下内容来实现相同的目的。代码位于onCreate方法内部: mTimer.scheduleAtFixedRate(new TimerT
所以我正在使用集合设计模式并使用数组列表。每当我尝试向数组列表中添加某些内容时,我都会收到 NPE。我可能错误地实现了该集合,因此出现了 NPE。 我不想复制我的整个代码,因为它太长了,所以我试图给你
我想将自定义对话框的一个区域设置为所选图像。如果我设置整个应用程序的背景图像,下面的代码可以进行一些重新安排。由于某种原因,当我移动它来设置自定义对话框的区域时,我收到以下错误: 错误: 11-03
所以我觉得自己像个白痴,但我正在尝试实现碰撞检测,并且我需要检查玩家旁边是否有方 block 。当我去检查时,我首先会看看我要找的瓷砖是否真的在那里。如果是,我将继续选择该图 block 并从中创建一
在 OS X 10.11 上,我们的应用程序用户会遇到一些没有堆栈跟踪的 NPE(请参阅 this stackoverflow-question)。我现在想自己创建一个来调试这种情况下的错误处理。 如
我有一个非常简单的 OpenAPI/Swagger 配置 (openapi.yaml): swagger: '2.0' info: title: My Service version: 1.0
我正在尝试为名为 getBestSellers() 的方法编写单元测试。 这里是: package bookstore.scraper.book.scrapingtypeservice; import
为什么我在以下作业中获得 NPE: mPyramid[row][column] = temp; 这是我的代码: Block temp; Block[][] pyramid =
为什么这段代码会导致NPE? Findbugs 给了我提示,这种情况可能会发生,而且有时确实会发生:-) 有什么想法吗? public Integer whyAnNPE() { return
我正在尝试运行客户端并访问字段来设置/获取值。当脚本启动时,我创建一个加载了 URLClassLoader 的客户端类的新实例,并将其分配给 gameApplet。 现在,下一段代码可以正常工作(访问
我是一名优秀的程序员,十分优秀!