【问题标题】:CalledFromWrongThreadException exercising JUnit tests on AndroidCalledFromWrongThreadException 在 Android 上执行 JUnit 测试
【发布时间】:2010-01-18 15:42:19
【问题描述】:

我是 JUnit 和 Android 的新手,很难找到与 Android 配合使用的良好测试文档。

我有一个测试项目,其中包含扩展 ActivityInstrumentationTestCase2 的类。检查 GUI 状态(启用什么、相对位置等)的简单测试按预期工作。但是,当我尝试执行按钮单击操作时,会引发错误的线程异常。有谁知道如何解决这个问题?

作为后续,有人对 Android 的测试或 TDD 的免费资源有什么好的建议吗?我正在使用 Eclipse/MotoDev。

谢谢

根据我调用每个按钮的方式,我可以获得不同的失败跟踪,但此处包括一个以供参考:

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRoot.checkThread(ViewRoot.java:2683)
at android.view.ViewRoot.playSoundEffect(ViewRoot.java:2472)
at android.view.View.playSoundEffect(View.java:8307)
at android.view.View.performClick(View.java:2363)
at com.android.tigerslair.demo1.test.GoTest.setUp(GoTest.java:49)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)

这是简单的 setup() 例程:

@Override
protected void setUp() throws Exception {
    super.setUp();
    TigersLair activity=getActivity();

    mGoBtn = (Button) activity.findViewById(R.id.go);
    mGoBtn.performClick();        
}

不管我是在setUp()中执行点击还是实际测试。

【问题讨论】:

    标签: java android junit


    【解决方案1】:

    您需要在 UIThread 中执行所有点击。

    这可以通过以下两个例子来完成。

    @UiThreadTest
    public void testApp() {
      TestApp activity = getActivity();
    
      Button mGoBtn = (Button) activity.findViewById(R.id.testbutton);
      mGoBtn.performClick();
    }
    

    public void testApp2() throws Throwable {
      TestApp activity = getActivity();
    
      final Button mGoBtn = (Button) activity.findViewById(R.id.testbutton);
      runTestOnUiThread(new Runnable() {
    
        @Override
        public void run() {
          mGoBtn.performClick();
        }
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      相关资源
      最近更新 更多