view.performLongClick()时发生机器人异常

问题描述 投票:0回答:2

我特别需要编写如下测试:

@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.robolectric.shadows.ViewTest.performLongClick_shouldClickOnView中检查了类似的测试,但我不知道为什么Robolectric中的那个有效而我的不起作用。顺便说一句,我正在使用Robolectric 2.3。

感谢您的帮助!

谢谢,程

android robolectric
2个回答
2
投票

您应该正在做shadowOf(view).performLongClick。

而且,这可能也不是创建您感兴趣的视图的最佳方法。尝试

view = new View(new Activity());

或使用LayoutInflater。

stacktrace表示问题在于创建上下文菜单,这是长按的默认行为。自动测试有效且您的测试失败的原因是它们覆盖了onLongClickListener。因此,只需尝试这样的事情:

        view.setOnLongClickListener(new View.OnLongClickListener() {
           @Override
           public boolean onLongClick(View v) {
               return true;
           }
        });

关键是要返回true,因此如果要单独测试,则上下文菜单不会被调用。


0
投票

我正在测试上下文菜单。从listView的一行调用它。这就是我的做法(在Kotlin中):

    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)

现在performClick起作用了。我只需要学习如何获取上下文菜单来测试这一菜单即可!

© www.soinside.com 2019 - 2024. All rights reserved.