在Android设备上查看UI元素测试

前端之家收集整理的这篇文章主要介绍了在Android设备上查看UI元素测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图用以下测试用例来测试简单的UI,
主要思想是在测试中设置一些UI文本(以模拟用户输入),然后主动单击事件.
public class StackTestCase 
extends ActivityInstrumentationTestCase2<Stack> 
{
private StackDemo mActivity;

private EditText eaten;
    public StuckTestCase() {
         super("com.crocodil.software.stack",Stack.class);


    }
    public StuckTestCase(Class<Stack> activityClass) {
         super("com.crocodil.software.stack",activityClass);

    }
    protected void setUp() throws Exception {
        super.setUp();
        mActivity = this.getActivity();
        mCount = (Button) mActivity.findViewById(com.crocodil.software.stack.R.id.action);
        eaten = (EditText) mActivity.findViewById(com.crocodil.software.stack.R.id.eaten);

    }

    public void testPreconditions() {
        assertNotNull(mStatus);
      }

    public void testSimpleDefaults(){
        double status = Double.valueOf(mStatus.getText().toString());
        eaten.setText(2);
        mCount.performClick();
        assertEquals((status-2),Double.valueOf(mStatus.getText().toString()));
    }

}

运行结果是异常 –

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.playSoundEffect(ViewRoot.java:2581)
at android.view.View.playSoundEffect(View.java:8516)
at android.view.View.performClick(View.java:2407)
at com.crocodil.software.stack.test.StackTestCase.testSimpleDefaults(StackTestCase.java:46)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
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)

每次访问UI元素时都会发生这种情况,我无法通过使用句柄或异步任务来避免这种情况.有什么建议么?

解决方法

这是一个老问题,但是我给你一个答案,以防万一有人绊倒.

您不允许从任何地方更改UI小部件的状态,但主线程(UI线程).你的performClick必须这样做:

mActivity.runOnUiThread(new Runnable() {
  @Override
  public void run() {
    mCount.performClick();
  }
});

但这不是全部,您还需要将您的仪器测试与ui同步,添加以下行:

getInstrumentation().waitForIdleSync();

同步线通常放在runOnUiThread()代码之后.

猜你在找的Android相关文章