关于Instrumentation 测试如何测试OnFling()方法
我现在写了一个测试类继承了ActivityInstrumentationTestCase2, 我只能利用sendKeys()方法模拟手机键的输入模拟UI的按键的事件。可我希望能测试用户在屏幕上滑动组件的效果,如何模拟呢?是使用Instrumentation.sendPointerSync()这个方法来实现吗?
我的测试方法如下:
MonthModel currentMonth = activity.getCurrentMonth();
final Instrumentation instrumentation = this.getInstrumentation();
assertNotNull(instrumentation);
long firstTime = SystemClock.uptimeMillis();
final MotionEvent firstEvent = MotionEvent.obtain(firstTime, firstTime,
MotionEvent.ACTION_DOWN, 100, 170, 0);
long secondTime = SystemClock.uptimeMillis();
final MotionEvent secondEvent = MotionEvent.obtain(secondTime,
secondTime, MotionEvent.ACTION_UP, 100, 340, 0);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
instrumentation.sendPointerSync(firstEvent);
instrumentation.sendPointerSync(secondEvent);
}
});
currentMonth = currentMonth.gotoPreviousMonth();
assertEquals(currentMonth, activity.getCurrentMonth());
不考虑业务逻辑,当我执行这个方法的时候,会产生如下的异常:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
at android.view.ViewRoot.requestLayout(ViewRoot.java:594)
at android.view.View.requestLayout(View.java:8125)
at android.view.View.setLayoutParams(View.java:4860)
at android.view.WindowManagerImpl.updateViewLayout(WindowManagerImpl.java:188)
at android.view.Window$LocalWindowManager.updateViewLayout(Window.java:428)
at android.app.Activity.onWindowAttributesChanged(Activity.java:1974)
at android.view.Window.setFlags(Window.java:638)
at android.view.Window.addFlags(Window.java:603)
at com.cybercom.canlendarApp.test.activity.CalendarAppTest.setUp(CalendarAppTest.java:37)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
希望有高手能为我解答疑惑,谢谢哈。