为 onTouch() 编写单元测试 android

Write unit test for onTouch() android

我的项目中有一个文本字段,并且 setOnTouchListener 与之关联。在 onTouch() 中,我在单击该文本字段后执行了预期的操作。

我需要为 onTouch() 编写单元测试用例。谁能帮帮我?

    public boolean onTouch(View v, MotionEvent event) { 

        final Intent intent;

        switch (v.getId()) { 

            case R.id.xyz: 
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(getString(R.string.xyz))); 
                startActivity(intent); 
                break;

            case R.id.abc: 
                intent = new Intent(Intent.ACTION_VIEW); 
                intent.setData(Uri.parse(getString(R.string.abc))); 
                startActivity(intent); 
                break; 

            default: 
                break;

        } 

        return false; 
}

所以我找到的方法是:

  • 使用 findViewById
  • 从预期 activity 获取所需视图
  • 创建那个 activity
  • 的对象
  • 调用 onTouch(view,null)
  • 无需关注运动事件的对象,因为它未在此单元测试中使用

我通过在 activity 中创建 OnTouchListener 变量对象实现了这一点。在测试中,对该对象调用了 onTouch。

    MotionEvent motionEvent = mock(MotionEvent.class);
    when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_DOWN);
    subject.onTouchListener.onTouch(subject,motionEvent);