Android view.performLongClick()时发生Robolectric异常
我特别需要编写一个测试,如下所示:Android view.performLongClick()时发生Robolectric异常,android,robolectric,Android,Robolectric,我特别需要编写一个测试,如下所示: @RunWith(RobolectricTestRunner.class) public class LongClickTest { @Test public void testPerformLongClick() { View view = new View(Robolectric.application); view.performLongClick(); } } 但它给了我以下错误: java.l
@RunWith(RobolectricTestRunner.class)
public class LongClickTest {
@Test
public void testPerformLongClick() {
View view = new View(Robolectric.application);
view.performLongClick();
}
}
但它给了我以下错误:
java.lang.NullPointerException
at android.view.View.showContextMenu(View.java:4154)
at android.view.View.performLongClick(View.java:4123)
at org.robobinding.widget.view.OnLongClickAttributeTest.longClickOnView(OnLongClickAttributeTest.java:34)
at org.robobinding.widget.view.OnLongClickAttributeTest.givenBoundAttribute_whenLongClickOnView_thenEventReceived(OnLongClickAttributeTest.java:27)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:250)
...
我在Robolectric自身org.roblectric.shadows.ViewTest.performLongClick\u shouldClickOnView中检查了一个类似的测试,但我不明白为什么Robolectric中的测试有效,而我的测试无效。顺便说一下,我使用的是机器人分子2.3
谢谢你的帮助
谢谢,
Cheng您应该执行shadowOf(视图)。执行长单击
而且,这可能不是创建您感兴趣的视图的最佳方式。试一试
view = new View(new Activity());
或者使用一个平放机。
stacktrace表明问题在于创建上下文菜单,这是长时间单击的默认行为。机器人测试成功而你的失败的原因是它们覆盖了onLongClickListener。
因此,请尝试以下方法:
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
关键是要返回true,这样上下文菜单就不会被调用,如果你想单独测试的话 我正在测试上下文菜单。它是从listView的一行调用的。我就是这样做的(在科特林):
现在performClick可以工作了。我只需要学习如何得到de上下文菜单来测试这个 你能发布你想要运行的确切代码吗?嗨,亚历克斯,谢谢。我已经更新了内容。如果您运行测试,您将得到相同的错误。我的测试不止这些,但这是我被卡住的部分。嗨,亚历克斯,谢谢你的回答。但在Robolectric 2.3中,没有这种方法长时间点击ShadowView。如果选中此测试,则在第178行执行长时间单击的方法应单击查看()。你会看到Robolectric也在做同样的事情。我对使用Activity或LayoutInflater不感兴趣,因为我说过我有特殊需要,测试一个框架而不是一个n应用程序。很抱歉,我没有注意stacktrace,我的错。我已经更新了我的答案,让我知道这是否适合你。谢谢,亚历克斯。我也通过调试找到了它。我会留下你的答案。我在Robolectric google group上发布了同样的问题,有一段时间没有回答。这就是我在这里发帖的原因。再次感谢您的努力!请解释这是如何回答这个问题的。空指针是视图实例化方式的副作用
val activity = buildActivity(MyActivity::class.java).create().get()
val customView = LayoutInflater.from(activity)
.inflate(R.layout.custom_xml, activity.my_list_view, false)
as MyCustomView
val linearLayout = activity.my_list_view.parent as LinearLayout
linearLayout.addView(customView)